Pages#
capturegraph-ui builds pages: a page function constructs components, and
the result is a Page — a website folder, index.html beside every file it
shows. The server declares a page at a position of
a target — a folder or file of the on-disk layout the schema fixes ahead of
time (on disk) — calls the function with the
value loaded there, and hosts the folder at that position's URL. One import
is the whole surface:
The package is two steps.
1. Build. The server calls a page function with the value at the
position it is declared at
(@cgserver.page); target below is
that value. Under @cgui.PageBuilder() the body reads as the page, top to
bottom: every component it constructs attaches to the innermost open stack
in construction order — the way, under
@cg.procedure, every node a procedure body constructs is
recorded into the graph rather than run — with cgui.HStack(): or
with cgui.VStack(): opens a nested stack for the block, and
cgui.Title(...) names the page and renders nothing in the body. Ordinary
Python does the rest: a for loop builds one PageLink per session, an
if decides whether to say something. The body is annotated -> None; the
wrapper the decorator returns is annotated -> cgui.Page.
import capturegraph as cg
import capturegraph_ui as cgui
class Session(cg.Struct):
photo: cg.Image
class PlantJournal(cg.Struct):
sessions: cg.Map[cg.Time, Session]
@cgui.PageBuilder()
def journal(target: PlantJournal) -> None:
cgui.Title("Plant Journal")
cgui.Markdown("## Sessions")
with cgui.HStack():
cgui.Stat("Sessions", len(target.sessions))
cgui.Stat("Days", len({instant.value.date() for instant in target.sessions.keys()}))
cgui.Gallery.of(target.sessions, lambda s: s.photo)
for instant, session in target.sessions.items():
cgui.PageLink(session, title=instant.value.date().isoformat())
The gallery shows each photo — HEIC, DNG or whatever the phone captured — as
a JPEG thumbnail it makes with
cgui.thumbnail, a recipe:
a @cg.pure_function, memoized in the
scratch — the content-addressed cache
directory the library manages — by the content of its arguments, so each
photo is decoded once however often the page is rebuilt. ImageViewer and
Timelapse transcode the same way at their own sizes; a JPEG already small
enough is shown as it is.
2. Render. Nothing is written until the page is built: page.build(),
or the scratch sealing the returned Page when the page function returns —
the normal path on the server, where @cgserver.page makes the function a
memoized pure_function. Each component then writes its HTML through one
Render context: the files it shows are staged under files/, the browser
libraries it needs under lib/, and index.html holds the rendered tree,
with <title> when the page named one
(what a page is on disk).
Outside a builder, a stack takes its children outright and
cgui.Page.declare(root, *, title=None) makes the page from the tree:
cgui.Page.declare(cgui.VStack(children=[cgui.Markdown("# Hi")]), title="Hi").
declare allocates the page's folder in the active scratch (the machine's
shared one unless configured otherwise; in tests, the cg_scratch fixture). Inside a builder children= is not needed — a stack given children
takes them back from the open stack they attached to, so they belong to it
alone. Only a component built inside a stack that has since closed doubles
when handed to a later children=. A hand-made folder holding an
index.html is a page as it stands: cgui.Page.load(folder) takes it,
stores it byte for byte, and reads page.title from the <title>.
The title is the page's name wherever it is listed: the browser tab, the
server's index card, the position's ~status
report. Derive it from the data rather than repeating the function's name.
Components#
Every component is a class in cgui, documented in the
API reference; its annotated fields
are its props, checked when it is built. Absence — the
cg.Missing a load
hands back for data that is not there — is handled at three levels:
- A component given
Missingfor any prop — orNonefor a prop without a default — renders as nothing.cgui.Stat("Wind", session.weather.wind_speed_mps)leaves the page when no weather was recorded,cgui.Stat("ISO", photo.exif().iso)when the photograph records none, andcgui.ImageViewer(crop(session.photo))when there is no photo, because a recipe called with aMissingargument returnsMissing. - A
Missingitem in a list,MaporArrayprop is left out and the rest is shown:cgui.Gallery(target.sessions.photo)skips a session whose photo never landed, and anofconstructor leaves out an entry its function returnsMissingorNonefor. - A
Scattercolumn keeps aMissingvalue as an unrecorded point. The columns stay the same length; the point drops out of the plot whenever that column is one of the two axes shown, and a column with nothing recorded is left out of the axis menus altogether.
Page code therefore reads the value it wants and lets absence fall out,
rather than guarding with cg.is_missing; guard only where absence changes
what to say.
A picture is any cg.StillImageFile — a
cg.Image, cg.Panorama or cg.Thumbnail, or a still-image scalar of your
own — so ImageViewer, Gallery and Timelapse take whichever a recipe
returns.
Instants show in the reader's time zone. A datetime or cg.Time given
to Stat, a MapViewer label, or a Time key captioning a Gallery or
Timelapse reaches the page as its ISO form, and the browser writes it in the
reader's own zone — cgui.Stat("Captured", session.time) needs no time zone
in the page code.
A page is self-contained: every browser library a component needs is copied
into the page under lib/ (the Stages column), and only MapViewer's
tiles are fetched, from OpenStreetMap.
| Component | Renders | Stages |
|---|---|---|
Title(text) |
Nothing in the body; sets the page's <title>. Raises outside a builder. |
|
VStack(children=[], gap=16) |
Children top to bottom; with opens it for the block and raises outside a builder. Outside one, pass children= instead. |
|
HStack(children=[], gap=16) |
Children side by side, wrapping when narrow; with likewise. |
|
Divider() |
A faint line across the page. | |
Padding(size=16) |
size pixels of empty space along the enclosing stack's axis. |
|
Markdown(text) |
CommonMark as prose; raw HTML is shown, not interpreted. | |
Stat(label, value, unit=None) |
One labelled figure; an instant shows in the reader's time zone. | |
ImageViewer(image, caption=None) |
One picture with an optional caption; it links nowhere. | |
Gallery(images) |
A grid of pictures — a list, Map or Array — captioned by key when keyed; Gallery.of for derived pictures. |
|
Timelapse(images) |
A Map of pictures (keyed by Time for time order) scrubbed with a slider; a plain list is not accepted. Timelapse.of likewise. |
|
MapViewer(locations, labels=None, marker="pin", outline=None, anchors=None) |
Markers on a map, popups from labels or the keys; "dot" plots hundreds close together, outline draws a boundary under them, an anchors point is joined to its marker by a dashed line; MapViewer.of links them. |
lib/leaflet |
Scatter(columns, default=None, groups=None, spread=3.0, spans=None, color=None, size=None) |
Points over named columns, either axis picked from a menu; each axis spans spread deviations either side of its column's mean, clamped to that column's range; a column that never varied spans one unit either way; a column named in spans always spans that fixed range. color and size name number columns that shade and size the points. Scatter.of builds the columns from typed records. |
lib/vega, lib/vega-lite, lib/vega-embed |
Rate(instants, groups=None, sigma=timedelta(minutes=10), fold=None) |
Events per minute, each spread as a Gaussian of sigma, stacked by group; across the whole span only the busy stretches are drawn, and fold="day" lays every day over one by the reader's local time of day. |
lib/vega, lib/vega-lite, lib/vega-embed |
Chart(spec, data=None) |
A Vega-Lite spec in full; data is a staged CSV, TSV or JSON file as a cg.Blob, the file scalar of any bytes. |
lib/vega, lib/vega-lite, lib/vega-embed |
PageLink(value, title=None) |
A link card to a value's page. | |
cgr.SplatViewer(model) |
A cgr.Splat PLY in an orbit viewer; shipped by capturegraph-recipes with its own JavaScript. |
lib/gsplat |
A Scatter plots columns, not entries. Its columns are one quantity per
point — frames.iso, sun.altitude, a plain list — every column the same
length, and the dict's keys are the axis menus and the axis titles.
Broadcast access builds a column: frames.exif.iso reads the field off every
element (containers), a Missing where an element
has none.
A column of instants (datetime or cg.Time) offers two choices in the
menus: the instant, read as a date, and its time of day, "Captured (time of
day)" — both in the reader's own time zone, so a page needs no zone of its
own.
Scatter.of takes arrays of records instead of naming every column: each
field the record's type marks with a
cg.Quantity becomes a column
labelled from it, and a dict adds columns of your own.
exif = photos.exif()
cgui.Scatter.of(
exif, # Exposure time (s), Aperture (f/), ISO, …
exif.gps, # Latitude (°N), Camera heading (°), …
weather, # Temperature (°C), Cloud cover, …
{"Captured": exif.instant},
default=("Captured (time of day)", "Cloud cover"),
)
A component of your own is a subclass of cgui.Component with annotated
props and an html method, and a browser library of your own ships as
package data — Adding a component.
Figures#
A chart the app shows — a guidance image an interceptor serves into an image
slot — is drawn on the server, so it cannot be a browser chart.
cgui.Figure draws one with
matplotlib in the house style (white paper, dark ink, type a phone can read at
full width) and keeps it as a PNG cg.Image when the
with block ends. The same image goes on a page with ImageViewer.
@cg.pure_function("need_chart/1")
def need_chart(hours: cg.Array[float], need: cg.Array[float]) -> cg.Image:
with cgui.Figure("When to photograph") as figure:
figure.axes.fill_between(list(hours), list(need))
figure.axes.set_xlabel("Time of day (h)")
return figure.image
panels=(3, 1) stacks panels sharing a horizontal axis, read back as
figure.panels. A figure allocates its PNG in the current call's workspace,
so it is drawn inside a cg.pure_function.
Links#
A value loaded from a target knows its position: the folder or file it was
read from, which the schema fixes ahead of time
(on disk).
cg.loaded_from(value) is that path, None for
a value built in memory (a .clone() included), and
cg.held(value) is true for a value whose files belong
to the scratch — a recipe's result — which is no position in the target
whatever path it has. The server hosts every page under
its position's URL plus a ~/ segment — /pages/<target>/sessions/<key>/~/
(URLs) — so a page links to another value's page
by one ../ out of ~/ and then the relative path between the two
positions on disk. From the root page a session links as
../sessions/<key>/; from a session page the root is ../../../, a sibling
../../<key>/, the page itself ../.
The position a page links from is page.at, the value the page is the page
of. The server sets it after the page function returns, so authors never do;
a test sets it by hand before build().
A link is a position URL, and only a position with a page declared exactly at its pattern answers, so link to values whose pattern the target declares a page at.
Only PageLink and the of constructors link; every other component
shows its data and links nowhere.
cgui.PageLink(value, title=None)is a card linking tovalue's page, captionedtitleor the value's folder name.valuemust have a position: the value the server passed the page function, any struct field, map entry or array element beneath it — all read from disk bycg.load— or the result of acg.loadof your own. A value built in memory, changed since it was loaded, or computed by a recipe fails the build with a message naming its type; so does aPageLinkin a page with noat.- Pictures and markers link through the
ofconstructors.Gallery.of(container, image),Timelapse.of(container, image)andMapViewer.of(container, location, label=None, anchor=None, marker="pin", outline=None)walk a loadedMaporArray(anArrayelement's entry is named [cg.Array.index_name(index)][capturegraph.Array.index_name], aMapentry by its encoded key) withpmap— the container's parallelmap, so the per-entry recipes run on the thread pool — and link each result to its entry's page, not to wherever the result lives. A thumbnail computed per session has no position of its own;Gallery.of(target.sessions, thumbnail)links it to its session. A function returningNoneorMissingleaves that entry out, soGallery.of(target.sessions, lambda s: thumbnail(s.photo))skips a session whose photo never landed. A function that raises on an entry, or returns aMissingcarrying an error, leaves that entry out the same way; the walk fails only when every entry fails. Over a container built in memory,ofdraws the items unlinked. - Without
of, nothing links:ImageViewer(session.photo),Gallery(target.sessions.photo),Timelapse(target.sessions.photo)andMapViewer(locations)show their pictures and markers as they are. A keyed collection still captions each item by its key.
The log as HTML#
The package also renders cg.logging: cgui.Notebook
is a sink (the notebook extra, inside a kernel) that redraws a Jupyter
cell with the log tree as it grows, and cgui.log.html(log) is the same
rendering the server stores as a page's build log (cgui.log.stylesheet()
and cgui.log.script() are the assets a live renderer needs beside it).
Writing a sink of your own is three methods.