GitHub

Example: Notes (desktop)

A Markdown notes app for pyweb desktop: its own window, data in the user's folder, and export through the system's Save dialog.

  • 125 lines of Python
  • 1 page
  • 4 server functions
  • 1478 B page JS (gzip)
This example is a desktop app: it opens in its own window. Run it locally:
Terminal
pip install 'pyweb-stack[desktop]'
pyweb desktop examples/desktop/app.pyweb    # or in a browser: pyweb dev examples/desktop/app.pyweb

#Source

examples/desktop/app.pyweb
"""Notes: a desktop app. Notes live in a database in your data folder; export one as a Markdown
file with the system's Save dialog.

Run it:      pyweb desktop app.pyweb      (or `pyweb dev app.pyweb` in a browser)
Package it:  pyweb build --desktop app.pyweb --package
"""

import re

from pyweb import App, Field, Markdown, Model, platform, server
from pyweb.desktop import Window
from pyweb.ui import Button, Theme, toast

app = App(title="Notes", database="sqlite:///notes.db", stylesheets=["/static/app.css"],
          theme=Theme.preset("ocean"), desktop=Window(width=1000, height=680, min_size=(640, 420)))


class Note(Model):
    title: str = Field(default="", max=120)
    body: str = ""


def all_notes():
    return [n.to_dict() for n in Note.query().order("-id")]


@server
def new_note() -> dict:
    return Note.create(title="Untitled", body="").to_dict()


@server
def save_note(note_id: int, title: str, body: str) -> dict:
    note = Note.get_or_404(note_id)
    note.title, note.body = title.strip()[:120] or "Untitled", body
    note.save()
    return note.to_dict()


@server
def delete_note(note_id: int) -> None:
    Note.get_or_404(note_id).delete()


@server
def export_note(note_id: int) -> str:
    """The system's Save dialog (desktop only); returns where the file went, or "" if cancelled."""
    from pyweb import desktop
    note = Note.get_or_404(note_id)
    name = re.sub(r"[^\w-]+", "-", note.title.lower()).strip("-") or "note"
    path = desktop.save_file(f"{name}.md", f"# {note.title}\n\n{note.body}\n", types=("Markdown (*.md)",))
    if path:
        toast("Exported", path, tone="success")
    return path or ""


@app.page("/")
def Notes():
    notes = all_notes()
    in_desktop = platform.desktop
    selected = notes[0]["id"] if notes else 0
    title = notes[0]["title"] if notes else ""
    body = notes[0]["body"] if notes else ""

    def pick(note):
        selected = note["id"]
        title = note["title"]
        body = note["body"]

    def add():
        note = new_note()
        notes = [note] + notes
        pick(note)

    def save():
        saved = save_note(selected, title, body)
        notes = [saved if n["id"] == selected else n for n in notes]

    def remove():
        delete_note(selected)
        notes = [n for n in notes if n["id"] != selected]
        if notes:
            pick(notes[0])
        else:
            selected = 0

    def export():
        save()
        export_note(selected)

    <main class="notes">
        <aside class="note-list">
            <div class="list-head">
                <h1>Notes</h1>
                <Button id="new" size="sm" onclick={add}>New</Button>
            </div>
            <ul>
                for note in notes:
                    <li animate="fade">
                        <button type="button" class={{"note": True, "active": note["id"] == selected}}
                                onclick={lambda: pick(note)}>{note["title"] or "Untitled"}</button>
                    </li>
            </ul>
            if not notes:
                <p class="empty">No notes yet.</p>
        </aside>
        <section class="editor">
            if selected:
                <input id="title" class="pw-control note-title" bind={title} aria-label="Title" />
                <div class="panes">
                    <textarea id="body" class="pw-control" bind={body} aria-label="Note"
                              placeholder="Write in Markdown…"></textarea>
                    <div class="preview markdown" aria-label="Preview"><Markdown text={body} /></div>
                </div>
                <div class="row">
                    <Button id="save" onclick={save}>Save</Button>
                    if in_desktop:
                        <Button id="export" variant="outline" onclick={export}>Export as Markdown…</Button>
                    <span class="spacer"></span>
                    <Button id="delete" variant="ghost" onclick={remove}>Delete</Button>
                </div>
            else:
                <p class="empty">Make a note with New.</p>
        </section>
    </main>

#What runs where

Output of pyweb inspect: every page variable, handler and server function, where it runs and why.

Output
page Notes  route=/
  browser  notes          reactive state: assigned in add(); initial value computed on the server and sent
  server   in_desktop     computed per request on the server; value sent because browser code reads it
  browser  selected       reactive state: assigned in pick(); initial value computed in the browser
  browser  title          reactive state: bound to an input (line 109); initial value computed in the browser
  browser  body           reactive state: bound to an input (line 111); initial value computed in the browser
  browser  pick           event handler (compiled to JavaScript)
  browser  add            event handler (compiled to JavaScript)
  browser  save           event handler (compiled to JavaScript)
  browser  remove         event handler (compiled to JavaScript)
  browser  export         event handler (compiled to JavaScript)
rpc POST /__pyweb/rpc/new_note  () -> dict
rpc POST /__pyweb/rpc/save_note  (note_id: int, title: str, body: str) -> dict
rpc POST /__pyweb/rpc/delete_note  (note_id: int) -> None
rpc POST /__pyweb/rpc/export_note  (note_id: int) -> str

#Generated JavaScript

The browser modules the compiler wrote (before minification). They import the shared runtime.

JavaScript
// Notes.js
import { h as $h, t as $t, dyn as $dyn, list as $list, when as $when, signal as $signal, computed as $computed, mount as $mount, onMount as $onMount, py as $py, rpc as $rpc, slot as $slot, onCleanup as $onCleanup, spreadProps as $spreadProps } from "./runtime.js";
import { markdown as $markdown } from "./markdown.js";
// button.pyweb
const { Button } = (() => {
  function Button($p) {
    const variant = $p["variant"] || (() => "default");
    const size = $p["size"] || (() => "md");
    const type = $p["type"] || (() => "button");
    const href = $p["href"] || (() => null);
    const loading = $p["loading"] || (() => false);
    const disabled = $p["disabled"] || (() => false);
    const onclick = $p["onclick"] || (() => null);
    const children = $p["children"] || (() => null);
    const attrs = $p["$rest"] || (() => ({}));
    const busy = $computed(() => ($py.truth(loading()) ? "true" : null));
    const part = $computed(() => $py.or($py.m(attrs(), "get", "data-part"), () => "button"));
    return [$when(() => $py.truth(href()), () => [$h("a", {"class": "pw-button", "data-part": () => part(), "data-variant": () => variant(), "data-size": () => size(), "href": () => href(), "aria-disabled": () => ($py.truth(disabled()) ? "true" : null), "onclick": (e) => { const f = onclick(); return f ? f(e) : undefined; }, "$spread7": () => attrs()}, () => [$dyn(() => children())])], () => [$h("button", {"class": "pw-button", "data-part": () => part(), "data-variant": () => variant(), "data-size": () => size(), "type": () => type(), "disabled": () => $py.or(disabled(), () => loading()), "aria-busy": () => busy(), "onclick": (e) => { const f = onclick(); return f ? f(e) : undefined; }, "$spread8": () => attrs()}, () => [
          $when(() => $py.truth(loading()), () => [$h("span", {"class": "pw-spinner", "aria-hidden": "true"})]),
          $dyn(() => children())
        ])])];
  }
  return { Button };
})();
function Notes($s) {
  const notes = $signal("notes" in $s ? $s["notes"] : null, "notes");
  const in_desktop = $s["in_desktop"];
  const selected = $signal("selected" in $s ? $s["selected"] : ($py.truth(notes()) ? $py.at($py.at(notes(), 0), "id") : 0), "selected");
  const title = $signal("title" in $s ? $s["title"] : ($py.truth(notes()) ? $py.at($py.at(notes(), 0), "title") : ""), "title");
  const body = $signal("body" in $s ? $s["body"] : ($py.truth(notes()) ? $py.at($py.at(notes(), 0), "body") : ""), "body");
  function pick(note) {
    selected($py.at(note, "id"));
    title($py.at(note, "title"));
    body($py.at(note, "body"));
  }
  async function add() {
    let note;
    note = (await $rpc("new_note", {}));
    notes($py.add([note], notes()));
    pick(note);
  }
  async function save() {
    let saved;
    saved = (await $rpc("save_note", {"note_id": selected(), "title": title(), "body": body()}));
    notes($py.iter(notes()).map((n) => (($py.eq($py.at(n, "id"), selected()) ? saved : n))));
  }
  async function remove() {
    (await $rpc("delete_note", {"note_id": selected()}));
    notes($py.iter(notes()).filter((n) => !$py.eq($py.at(n, "id"), selected())));
    if ($py.truth(notes())) {
      pick($py.at(notes(), 0));
    } else {
      selected(0);
    }
  }
  async function export_() {
    (await save());
    (await $rpc("export_note", {"note_id": selected()}));
  }
  return [$h("main", {"class": "notes"}, () => [
      $h("aside", {"class": "note-list"}, () => [
        $h("div", {"class": "list-head"}, () => [
          $h("h1", null, () => [$t("Notes")]),
          Button({"size": () => "sm", "onclick": () => add, "children": () => [$t("New")], "$rest": () => ({"id": "new"})})
        ]),
        $h("ul", null, () => [$list(() => notes(), (note) => [$h("li", {"data-pw-motion": JSON.stringify({"animate": "fade"}), "style": ((i, s) => s)(null, null, null, "fade")}, () => [$h("button", {"type": "button", "class": () => ({"note": true, "active": $py.eq($py.at(note, "id"), selected())}), "onclick": (() => (pick(note)))}, () => [$t($py.text($py.or($py.at(note, "title"), () => "Untitled")))])])])]),
        $when(() => !$py.truth(notes()), () => [$h("p", {"class": "empty"}, () => [$t("No notes yet.")])])
      ]),
      $h("section", {"class": "editor"}, () => [$when(() => $py.truth(selected()), () => [
          $h("input", {"id": "title", "class": "pw-control note-title", "$bind": title, "aria-label": "Title"}),
          $h("div", {"class": "panes"}, () => [
            $h("textarea", {"id": "body", "class": "pw-control", "$bind": body, "aria-label": "Note", "placeholder": "Write in Markdown\u2026"}),
            $h("div", {"class": "preview markdown", "aria-label": "Preview"}, () => [$markdown(() => body(), null)])
          ]),
          $h("div", {"class": "row"}, () => [
            Button({"onclick": () => save, "children": () => [$t("Save")], "$rest": () => ({"id": "save"})}),
            $when(() => $py.truth(in_desktop), () => [Button({"variant": () => "outline", "onclick": () => export_, "children": () => [$t("Export as Markdown\u2026")], "$rest": () => ({"id": "export"})})]),
            $h("span", {"class": "spacer"}),
            Button({"variant": () => "ghost", "onclick": () => remove, "children": () => [$t("Delete")], "$rest": () => ({"id": "delete"})})
          ])
        ], () => [$h("p", {"class": "empty"}, () => [$t("Make a note with New.")])])])
    ])];
}
$mount("Notes", Notes);
Edit this page on GitHub