Tutorial: The Same App as a Project¶
The Tutorial builds a Tasks app in one flat folder, naming every file by its path. This tutorial builds the same app as a project: a folder with a place for each kind of file, where Tesserae finds a file by its name. Read it beside the first one, or instead of it: the app, its screens and its behaviour are the same, and what changes is where the files are and how little code it takes to join them.
Every step is a project folder in
examples/tutorial_project/
that Tesserae's tests run. The page shows every file a step adds or changes, so each step can be followed on its own; the
flat Tutorial explains the views and ViewModels in more depth.
Flat or a project?¶
| A flat folder | A project | |
|---|---|---|
| Made by | you, file by file | tesserae new tasks, then your own files |
| Layout | every file side by side | Views/, ViewModels/, Themes/, Styles/ |
| Open a screen | app.open_view("Tasks"), with search=["."] so views are found in the folder |
app.open_view("Main") |
| A ViewModel | an import, then app.bind(TasksViewModel) |
app.bind(app.project.viewmodel("Main")): no import |
| A theme or stylesheet | App(custom_theme=HERE / "Brand_Theme.tdl") |
App(custom_theme="Brand") |
| A view of your own | next to the view that uses it | Views/, from any view |
| Good for | one screen, a sketch, a single file to share | an app with several screens and its own look |
Neither is a mode: a project is a flat folder with the files sorted, and paths still work in a project. Start flat
and sort the files into folders when there are too many to find; or start with tesserae new and never write a
path.
1. A new project¶
tesserae new tasks
cd tasks
source .venv/bin/activate # Windows: .venv\Scripts\activate
python app.py
tesserae new makes the folders, a Main screen that counts clicks, and a virtual environment with Tesserae in
it (--no-venv skips the environment). Its files are in the current view language already; replace the screen and
app.py with the Tasks app's:
tasks/
app.py
Views/Main_View.tdl
ViewModels/Main_ViewModel.py
Components/ Themes/ Styles/ empty for now; Components/ is not used here, a view of your own goes in Views/
---
TDL: 0.2
Name: Main
Tesserae: "0.6"
---
Container {
Name: Main
Style { Flex_Direction: vertical, Width: 100%, Height: 100%, Gap: 12, Padding: 24, Background: surface }
Children {
Text {
Name: title
Text: Tasks
Typography_Role: headline_medium
Style { Foreground: on_surface }
}
Text {
Name: summary
Text: <| summary |>
Typography_Role: body_large
Style { Foreground: on_surface_variant }
}
Button {
Name: add
Label: "Add a task"
Variant: filled
Handlers {
On_Click: add_task
}
}
}
}
from tess_ui import Computed, Signal, ViewModel
class MainViewModel(ViewModel):
views = "Main" # the view it serves: the name after `View` at the top of Tasks_View.tdl
def __init__(self):
super().__init__()
self.tasks = Signal([])
self.summary = Computed(lambda: f"{len(self.tasks.get())} tasks")
def add_task(self):
self.tasks.update(lambda tasks: [*tasks, f"Task {len(tasks) + 1}"])
from pathlib import Path
from tess_ui import App
HERE = Path(__file__).parent
app = App(width=420, height=520, title="Tasks", root=HERE, theme_seed=(0x0B, 0x6B, 0x58, 0xFF))
app.bind(app.project.viewmodel("Main")) # ViewModels/Main_ViewModel.py, the class MainViewModel
app.open_view("Main") # Views/Main_View.tdl
app.show("Main")
app.run()
- Paired by name. The view is named
Mainand its ViewModel serves"Main".app.open_view("Main")opensViews/Main_View.tdl, andapp.project.viewmodel("Main")is the classMainViewModelinViewModels/Main_ViewModel.py. There is no import and no path: the flatapp.pyneeded both. root=HEREsays where the project is, so it runs from any folder:python tasks/app.py.- The view and ViewModel are the flat Tutorial's, renamed
TaskstoMain.
2. A list of views¶
A task row is a view of its own, in the same folder as the screen:
---
TDL: 0.2
Name: TaskItem
Tesserae: "0.6"
---
# One row. A view with `params:` is a component: Tasks_View.yaml calls it as `widget: TaskItem`.
Container {
Params {
Task { Type: dict, Required: true }
On_Toggle { Type: handler }
On_Remove { Type: handler }
}
Style { Flex_Direction: horizontal, Align_Content: left, Gap: 8, Width: 100% }
Children {
Checkbox {
Name: done
Checked: <| task.done |>
Label: <| task.text |>
Style { Flex: expand_horizontal }
Handlers {
On_Change: on_toggle
}
}
IconButton {
Name: remove
Icon: close
Label: Remove
Handlers {
On_Click: on_remove
}
}
}
}
---
TDL: 0.2
Name: Main
Tesserae: "0.6"
---
Container {
Name: Main
Style { Flex_Direction: vertical, Width: 100%, Height: 100%, Gap: 12, Padding: 24, Background: surface }
Children {
Text {
Name: title
Text: Tasks
Typography_Role: headline_medium
Style { Foreground: on_surface }
}
Text {
Name: summary
Text: <| summary |>
Typography_Role: body_large
Style { Foreground: on_surface_variant }
}
Button {
Name: add
Label: "Add a task"
Variant: filled
Handlers {
On_Click: add_task
}
}
Container {
Name: list
Style { Flex_Direction: vertical, Gap: 4, Width: 100% }
Children {
For task In <| tasks |> Key <| task.id |> {
TaskItem {
Name: row
Task: <| task |>
On_Toggle: "toggle(task.id)"
On_Remove: "remove(task.id)"
}
}
}
}
}
}
from tess_ui import Computed, Signal, ViewModel
class MainViewModel(ViewModel):
views = "Main"
def __init__(self):
super().__init__()
self.tasks = Signal([]) # a list of {"id", "text", "done"}: the one source of truth
self._next_id = 1
self.summary = Computed(lambda: f"{len(self.tasks.get())} tasks")
def add_task(self):
task = {"id": self._next_id, "text": f"Task {self._next_id}", "done": False}
self._next_id += 1
self.tasks.update(lambda tasks: [*tasks, task])
def toggle(self, task_id):
self.tasks.update(lambda tasks: [{**t, "done": not t["done"]} if t["id"] == task_id else t for t in tasks])
def remove(self, task_id):
self.tasks.update(lambda tasks: [t for t in tasks if t["id"] != task_id])
TaskItem { }findsViews/TaskItem_View.tdlby its name, wherever the view that calls it is. The flat version needssearch=["."]to say where its views are.- The row has no ViewModel: it takes the task and two handlers as params, and
Main's ViewModel does the work.
3. Styling in files¶
Themes and stylesheets each have a folder, and the app names them:
---
TDL: 0.2
Name: Brand
Tesserae: "0.6"
---
Theme {
Seed: "#0B6B58"
Typography {
Headline_Medium { Font_Weight: 600 }
}
}
---
TDL: 0.2
Name: Tasks
Tesserae: "0.6"
---
Styles {
Rule {
Widget: Container
Classes: [page]
Style { Flex_Direction: vertical, Width: 100%, Height: 100%, Gap: 12, Padding: 24, Background: surface }
}
Rule { Widget: Text, Classes: [heading], Style { Foreground: on_surface } }
Rule { Widget: Text, Classes: [muted], Style { Foreground: on_surface_variant } }
# a rule for a view of your own: every TaskItem is a row
Rule { Widget: TaskItem, Style { Flex_Direction: horizontal, Align_Content: left, Gap: 8, Width: 100% } }
Rule { Widget: Container, Classes: [rows], Style { Flex_Direction: vertical, Gap: 4, Width: 100% } }
# the add button, a tertiary one: a rule for Button goes over the one Tesserae ships
Rule { Widget: Button, Variant: filled, Style { Background: tertiary } }
Rule { Widget: Button, Variant: filled, Part: label, Style { Foreground: on_tertiary } }
}
---
TDL: 0.2
Name: Main
Tesserae: "0.6"
---
Container {
Name: Main
Classes: [page]
Children {
Text {
Name: title
Classes: [heading]
Text: Tasks
Typography_Role: headline_medium
}
Text {
Name: summary
Classes: [muted]
Text: <| summary |>
Typography_Role: body_large
}
Button {
Name: add
Label: "Add a task"
Variant: filled
Style { Width: 140 }
Handlers {
On_Click: add_task
}
}
Container {
Name: list
Classes: [rows]
Children {
For task In <| tasks |> Key <| task.id |> {
TaskItem {
Name: row
Task: <| task |>
On_Toggle: "toggle(task.id)"
On_Remove: "remove(task.id)"
}
}
}
}
}
}
---
TDL: 0.2
Name: TaskItem
Tesserae: "0.6"
---
Container {
Params {
Task { Type: dict, Required: true }
On_Toggle { Type: handler }
On_Remove { Type: handler }
}
Children {
Checkbox {
Name: done
Checked: <| task.done |>
Label: <| task.text |>
Style { Flex: expand_horizontal }
Handlers {
On_Change: on_toggle
}
}
IconButton {
Name: remove
Icon: close
Label: Remove
Handlers {
On_Click: on_remove
}
}
}
}
from pathlib import Path
from tess_ui import App
HERE = Path(__file__).parent
app = App(
width=420,
height=520,
title="Tasks",
root=HERE,
custom_theme="Brand", # Themes/Brand_Theme.tdl: the colours, made from one seed
stylesheet="Tasks", # Styles/Tasks_Stylesheet.tdl: the look of every screen
)
app.bind(app.project.viewmodel("Main"))
app.open_view("Main")
app.show("Main")
app.run()
custom_theme="Brand"isThemes/Brand_Theme.tdl, andstylesheet="Tasks"isStyles/Tasks_Stylesheet.tdl.- The stylesheet holds rules for your own views (
Widget: TaskItem) and for ones Tesserae ships (Widget: Button, here a tertiary button), over the shipped look.
4. A view of your own¶
Any view says Stat, wherever it is, because every view in Views/ is found by its name:
---
TDL: 0.2
Name: Stat
Tesserae: "0.6"
---
# A number with a label under it, called as `widget: Stat`. Its look is its rules in Tasks_Stylesheet.yaml.
Container {
Params {
Label { Type: str, Required: true }
Value { Type: str, Required: true }
}
Children {
Text {
Name: value
Text: <| value |>
Typography_Role: title_large
}
Text {
Name: label
Text: <| label |>
Typography_Role: label_medium
}
}
}
---
TDL: 0.2
Name: Main
Tesserae: "0.6"
---
Container {
Name: Main
Classes: [page]
Children {
Text {
Name: title
Classes: [heading]
Text: Tasks
Typography_Role: headline_medium
}
Container {
Name: stats
Classes: [row]
Children {
Stat {
Name: open
Label: Open
Value: <| open_text |>
}
Stat {
Name: finished
Label: Done
Value: <| done_text |>
}
}
}
Button {
Name: add
Label: "Add a task"
Variant: filled
Style { Width: 140 }
Handlers {
On_Click: add_task
}
}
Container {
Name: list
Classes: [rows]
Children {
For task In <| tasks |> Key <| task.id |> {
TaskItem {
Name: row
Task: <| task |>
On_Toggle: "toggle(task.id)"
On_Remove: "remove(task.id)"
}
}
}
}
}
}
---
TDL: 0.2
Name: Tasks
Tesserae: "0.6"
---
Styles {
Rule {
Widget: Container
Classes: [page]
Style { Flex_Direction: vertical, Width: 100%, Height: 100%, Gap: 12, Padding: 24, Background: surface }
}
Rule { Widget: Text, Classes: [heading], Style { Foreground: on_surface } }
Rule { Widget: Text, Classes: [muted], Style { Foreground: on_surface_variant } }
# a rule for a view of your own: every TaskItem is a row
Rule { Widget: TaskItem, Style { Flex_Direction: horizontal, Align_Content: left, Gap: 8, Width: 100% } }
Rule { Widget: Container, Classes: [rows], Style { Flex_Direction: vertical, Gap: 4, Width: 100% } }
# the add button, a tertiary one: a rule for Button goes over the one Tesserae ships
Rule { Widget: Button, Variant: filled, Style { Background: tertiary } }
Rule { Widget: Button, Variant: filled, Part: label, Style { Foreground: on_tertiary } }
Rule { Widget: Container, Classes: [row], Style { Flex_Direction: horizontal, Gap: 12 } }
# the look of Stat: a rule for the widget, and one for each of its named parts
Rule {
Widget: Stat
Style { Flex_Direction: vertical, Align_Content: top, Width: 96, Padding: 12, Background: secondary_container, Corner_Radius: medium }
}
Rule { Widget: Stat, Part: value, Style { Foreground: on_secondary_container } }
Rule { Widget: Stat, Part: label, Style { Foreground: on_secondary_container } }
}
from tess_ui import Computed, Signal, ViewModel
class MainViewModel(ViewModel):
views = "Main"
def __init__(self):
super().__init__()
self.tasks = Signal([]) # a list of {"id", "text", "done"}: the one source of truth
self._next_id = 1
# a text property wants a string, so the counts are strings
self.open_text = Computed(lambda: str(sum(1 for t in self.tasks.get() if not t["done"])))
self.done_text = Computed(lambda: str(sum(1 for t in self.tasks.get() if t["done"])))
def add_task(self):
task = {"id": self._next_id, "text": f"Task {self._next_id}", "done": False}
self._next_id += 1
self.tasks.update(lambda tasks: [*tasks, task])
def toggle(self, task_id):
self.tasks.update(lambda tasks: [{**t, "done": not t["done"]} if t["id"] == task_id else t for t in tasks])
def remove(self, task_id):
self.tasks.update(lambda tasks: [t for t in tasks if t["id"] != task_id])
Views/Stat_View.tdlis the structure, and its look is theStatrules in the stylesheet, as in the flat Tutorial. One folder holds every view, so reusing one in another screen needs no path.
5. A second screen¶
Add Views/Settings_View.tdl and ViewModels/Settings_ViewModel.py (tesserae add screen Settings writes a starting
pair; The tesserae command says what it makes), then fill them in and share state through the app:
---
TDL: 0.2
Name: Settings
Tesserae: "0.6"
---
Container {
Name: Settings
Classes: [page]
Children {
Text {
Name: title
Classes: [heading]
Text: Settings
Typography_Role: headline_medium
}
TextField {
Name: name
Label: "Your name"
Text: <| name |>
Style { Width: 240 }
}
Container {
Name: buttons
Classes: [row]
Children {
Button {
Name: theme
Label: "Light or dark"
Variant: outlined
Handlers {
On_Click: toggle_dark
}
}
Button {
Name: back
Label: Back
Variant: text
Disabled: <| not app.can_go_back |>
Handlers {
On_Click: go_back
}
}
}
}
}
}
---
TDL: 0.2
Name: Main
Tesserae: "0.6"
---
Container {
Name: Main
Classes: [page]
Children {
Text {
Name: title
Classes: [heading]
Text: <| app.state.user |>'s tasks
Typography_Role: headline_medium
}
Container {
Name: stats
Classes: [row]
Children {
Stat {
Name: open
Label: Open
Value: <| open_text |>
}
Stat {
Name: finished
Label: Done
Value: <| done_text |>
}
}
}
Container {
Name: buttons
Classes: [row]
Children {
Button {
Name: add
Label: "Add a task"
Variant: filled
Handlers {
On_Click: add_task
}
}
Button {
Name: settings
Label: Settings
Variant: text
Handlers {
On_Click: open_settings
}
}
}
}
Container {
Name: list
Classes: [rows]
Children {
For task In <| tasks |> Key <| task.id |> {
TaskItem {
Name: row
Task: <| task |>
On_Toggle: "toggle(task.id)"
On_Remove: "remove(task.id)"
}
}
}
}
}
}
from tess_ui import ViewModel
class SettingsViewModel(ViewModel):
views = "Settings"
def __init__(self, state):
super().__init__()
self.name = state.user # the shared Signal itself: a bare reference to a Signal is two-way
def toggle_dark(self):
self.app.set_dark(not self.app.dark) # every screen switches, in place
def go_back(self):
self.app.back()
from tess_ui import Computed, Signal, ViewModel
class MainViewModel(ViewModel):
views = "Main"
def __init__(self):
super().__init__()
self.tasks = Signal([]) # a list of {"id", "text", "done"}: the one source of truth
self._next_id = 1
# a text property wants a string, so the counts are strings
self.open_text = Computed(lambda: str(sum(1 for t in self.tasks.get() if not t["done"])))
self.done_text = Computed(lambda: str(sum(1 for t in self.tasks.get() if t["done"])))
def add_task(self):
task = {"id": self._next_id, "text": f"Task {self._next_id}", "done": False}
self._next_id += 1
self.tasks.update(lambda tasks: [*tasks, task])
def toggle(self, task_id):
self.tasks.update(lambda tasks: [{**t, "done": not t["done"]} if t["id"] == task_id else t for t in tasks])
def remove(self, task_id):
self.tasks.update(lambda tasks: [t for t in tasks if t["id"] != task_id])
def open_settings(self):
self.app.navigate("Settings") # a step the user can go back from
import sys
from pathlib import Path
from tess_ui import App, Signal
HERE = Path(__file__).parent
class AppState:
"""What every screen shares: `self.state` in a ViewModel, `app.state` in a view."""
def __init__(self):
self.user = Signal("Ada")
state = AppState()
app = App(width=420, height=520, title="Tasks", root=HERE, custom_theme="Brand", stylesheet="Tasks", state=state)
app.bind(app.project.viewmodel("Main"))
app.bind(app.project.viewmodel("Settings")(state)) # a ViewModel you made yourself
app.open_view("Main")
app.open_view("Settings")
app.route("", "Main")
app.route("settings", "Settings")
app.navigate_to(sys.argv[1] if len(sys.argv) > 1 else "") # a route: `python app.py settings`
app.run()
- Nothing is imported:
app.project.viewmodel("Settings")finds the class, and the routesettingsopens the screen (python app.py settings). state=stateis shared as it is in the flat Tutorial: the app owns it, a view readsapp.state.userand a ViewModel readsself.state.SettingsViewModelis made with it, so its field can edit the Signal.
6. A custom window¶
The app's frame is one more view, a Window file in Views/, opened by name. It holds the title bar, a rail, a status
bar, and the two screens as calls with a Route:
---
TDL: 0.2
Name: Window
Tesserae: "0.6"
---
# The frame around the screens. With no OS title bar, the window's own title bar is the one at the top.
Window {
Name: Window
Title: Tasks
Borderless: true # no OS title bar: the title bar below is the window's
Min_Width: 480
Min_Height: 360
Style { Width: 640, Height: 480, Background: surface, Flex_Direction: vertical }
Title_Bar { Title: Tasks, Style { Background: primary_container }, Buttons: [minimize, maximize, close] }
Children {
Container {
Name: body
Style { Flex: fill, Flex_Direction: horizontal }
Children {
NavigationRailScreens {
Name: nav
Items {
Item { Label: Tasks, Icon: home, Screen: Main }
Item { Label: Settings, Icon: settings, Screen: Settings }
}
}
Container {
Name: screens
Style { Flex: fill }
Children {
Main {
Name: main
Route: ""
Style { Flex: fill }
}
Settings {
Name: settings
Route: settings
Style { Flex: fill }
}
}
}
}
}
StatusBar {
Name: status
Text: Ready
Style { Width: 100% }
}
}
}
---
TDL: 0.2
Name: Settings
Tesserae: "0.6"
---
Container {
Classes: [page]
Children {
Text {
Name: title
Classes: [heading]
Text: Settings
Typography_Role: headline_medium
}
TextField {
Name: name
Label: "Your name"
Text: <| name |>
Style { Width: 240 }
}
Container {
Name: buttons
Classes: [row]
Children {
Button {
Name: theme
Label: "Light or dark"
Variant: outlined
Handlers {
On_Click: toggle_dark
}
}
}
}
}
}
---
TDL: 0.2
Name: Main
Tesserae: "0.6"
---
# A screen of the window: it has no `name:` and no ViewModel of its own. It reads the names of the one that serves Window_View.yaml.
Container {
Classes: [page]
Children {
Text {
Name: title
Classes: [heading]
Text: <| app.state.user |>'s tasks
Typography_Role: headline_medium
}
Container {
Name: stats
Classes: [row]
Children {
Stat {
Name: open
Label: Open
Value: <| open_text |>
}
Stat {
Name: finished
Label: Done
Value: <| done_text |>
}
}
}
Button {
Name: add
Label: "Add a task"
Variant: filled
Style { Width: 140 }
Handlers {
On_Click: add_task
}
}
Container {
Name: list
Classes: [rows]
Children {
For task In <| tasks |> Key <| task.id |> {
TaskItem {
Name: row
Task: <| task |>
On_Toggle: "toggle(task.id)"
On_Remove: "remove(task.id)"
}
}
}
}
}
}
from tess_ui import Computed, Signal, ViewModel
class WindowViewModel(ViewModel):
"""Serves Window_View.tdl, and so the Tasks and Settings screens in it: they read these names."""
views = "Window"
def __init__(self, state):
super().__init__()
self.name = state.user # Settings: the shared Signal itself, so the field is two-way
self.tasks = Signal([]) # Tasks: a list of {"id", "text", "done"}
self._next_id = 1
self.open_text = Computed(lambda: str(sum(1 for t in self.tasks.get() if not t["done"])))
self.done_text = Computed(lambda: str(sum(1 for t in self.tasks.get() if t["done"])))
def add_task(self):
task = {"id": self._next_id, "text": f"Task {self._next_id}", "done": False}
self._next_id += 1
self.tasks.update(lambda tasks: [*tasks, task])
def toggle(self, task_id):
self.tasks.update(lambda tasks: [{**t, "done": not t["done"]} if t["id"] == task_id else t for t in tasks])
def remove(self, task_id):
self.tasks.update(lambda tasks: [t for t in tasks if t["id"] != task_id])
def toggle_dark(self):
self.app.set_dark(not self.app.dark)
import sys
from pathlib import Path
from tess_ui import App, Signal
HERE = Path(__file__).parent
class AppState:
"""What every screen shares: `self.state` in a ViewModel, `app.state` in a view."""
def __init__(self):
self.user = Signal("Ada")
state = AppState()
app = App(title="Tasks", root=HERE, custom_theme="Brand", stylesheet="Tasks", state=state)
app.bind(app.project.viewmodel("Window")(state))
app.open_view("Window") # Views/Window_View.tdl: the window, its rail and its screens
app.navigate_to(sys.argv[1] if len(sys.argv) > 1 else "")
app.run()
- The rail replaces the Settings button, so the screens lose their Back and Settings buttons.
app.open_view("Window")opensViews/Window_View.tdl. ItsMain { }andSettings { }calls, with aRoute, are the screens: each is registered under its view's name (Main,Settings), soapp.pyno longer opens or routes them.- A routed screen has no ViewModel of its own: it reads the names of the one that serves the window, so
Main_ViewModel.pyandSettings_ViewModel.pyare now one,Window_ViewModel.py: delete the two old files, which nothing uses any more. - The window's
Borderless: trueandTitle_Barmake the window's own title bar; the rail is aNavigationRailScreenswhoseScreennames the screens.
Where next¶
- Projects: the rest of finding files by name, more folders to search (
search=), looking through the whole project (recursive=True), and what a name in two places does. - The
tesseraecommand:new,add screen,build. - Tutorial: the same app with every file named by its path, and its TDL for each step.