# Design of the web backend This page explains how `composeui.webcore` handles requests, updates the browser, and manages sessions. The user guide's [Web backend](../user-guide/running-the-app.md#web-backend) section covers what users see. For uploads, downloads, and streaming, see [File transfers on the web](web-file-transfers.md). ## The web backend The web backend renders HTML on the server and updates the page with htmx. - **The id is the rendered object.** The web has no live widget between two requests. A web renderer's rendered object is the id of its HTML fragment, `cui-{id(view)}-{role}`. - **One main view per session.** Each browser session has its own main view, in a `WebSession` (`session.py`). `WebApplication.connect` records each connection, and connects it again on the main view of each new session. - **Events go in, fragments come out.** An event goes to the server. The response sends back the fragments that the event changed, and htmx swaps them into the page. ## A button click on the web This is the click of [A button click](architecture.md#a-button-click) on the web, step by step:  1. **The browser posts the event.** The button's fragment (`WebButtonRenderer.to_html`) has `hx-post="/_composeui/widget/{id}"` and `hx-vals` with `event=click`. Its `hx-swap="none"` tells htmx not to swap the button with the response. 2. **The middleware checks the request.** `create_starlette_app` in `webapplication.py` adds the middleware. `SecurityHeadersMiddleware` (`headers.py`) adds the security headers to every response. `BodySizeLimitMiddleware` (`limits.py`) refuses a body that is too large. `SameOriginMiddleware` (`origin.py`) refuses a request from another origin. Starlette's `SessionMiddleware` reads the signed session cookie. 3. **The route finds the session.** `widget_event` (`routes.py`) gets the session from the cookie's id. When the session is gone, or did not serve the page, the response has `HX-Refresh`. The page reloads, with the cookie's session or a new one. Otherwise, the route calls `WebSession.handle_event` in a thread: the app's callbacks are synchronous code, and must not block the event loop. 4. **The session dispatches the event.** `handle_event` finds the renderer by its id in the session's own `renderers`. An id of another session is not found. `_respond` takes the session's lock and opens `collect_dirty()`, a set of dirty renderers for this request. Then it calls `WebButtonRenderer.dispatch`, which refuses the click when the button is disabled. 5. **The signal runs the callback.** `dispatch` emits `clicked`. The callback sets `label.text = "Done"`. 6. **The label's renderer becomes dirty.** `notify_renderer`, the `on_setattr` hook of every view field, calls the renderer's `refresh_attribute("text", ...)`. The handler in the `_refresh_dispatcher` of `WebLabelRenderer` is `_mark_dirty`. It only adds the renderer to the dirty set: the renderer renders nothing yet. 7. **The session renders the dirty fragments.** `_respond` adds the renderers that a thread changed since the last response (`take_pending`) to the dirty ones. `render_dirty` calls `to_html(oob=True)` on each, which adds `hx-swap-oob="true"` to the root element. It drops a fragment that another dirty fragment contains, else htmx would swap it twice. 8. **The session adds the page's fragments.** When the event changed the main view's title, language, or running jobs, `_respond` adds their fragments too. When the event opened another page, `_respond` also returns the page's address. 9. **The route responds.** `_widget_response` sends the fragments as HTML. With a new page, it adds `HX-Push-Url`, which puts the address in the browser's history. When the app closed (the Exit action), it drops the session and responds with `HX-Redirect` to `/`. 10. **htmx swaps the fragments.** htmx puts each `hx-swap-oob` fragment in place of the element with the same id. The label shows "Done". The button stays as it is. When the app has [reactive methods](architecture.md#reactive-methods), they run once `dispatch` returns, in the batch that `_respond` opens around it, and before step 7. The fields that they set mark their renderers dirty, as in step 6, so their fragments go out in the same response. The other routes follow the same steps. `widget_file` gives an upload to the session in place of a form. `jobs_poll` runs no event: its response sends the changes that the threads made. ## Requests and updates - **htmx requests and responses.** The browser sends htmx requests to Starlette. Renderers build HTML without a template engine. `Markup.format()` escapes plain strings and preserves fragments already marked as `Markup`. Do not mark user input as safe HTML. - **The renderers' modules.** `webrenderer.py` holds the base `WebRenderer` and the helpers that the renderers share, such as `_view_html` and the icons. Each family of renderers has its module in `_renderers/`: `inputs.py` (text, numbers, dates), `controls.py` (check boxes, buttons, sliders), `choices.py` (also the tree), `content.py` (labels, images, Markdown, consoles, logs, metrics, the notification, the status bar), `charts.py`, `graphics.py` (maps, drawings), `tables.py`, `files.py` (path fields, uploads, the server's files), `forms.py`, `actions.py` (menus, toolbars), `dialogs.py`, `containers.py` (rows, columns, panes, lists, tabs, pages) and `navigation.py` (the main view, its sidebar and router). A module holds one family: split one that starts to mix two, whatever its length. Such a module imports `webrenderer.py`. So `renderers.py`, not `webrenderer.py`, maps each renderer key to its class, written out, not discovered. The base names no renderer at run time: it asks each one, through `is_drawn_apart` (a dialog, drawn at the end of the page) and `shows` (a router's or a tab's page shown). A form row's label is always a `WebFormLabelRenderer`, which the base only casts to. When the base must treat a renderer apart, add such a hook with a default, not an `isinstance` check, which would tie that renderer to the base's module. `changes.py` collects the renderers that a request changes (`collect_dirty`), and `rendertarget.py` holds a session's view tree and its lock (`RenderTarget`). - **No code in the markup.** The page's `Content-Security-Policy` (`headers.py`) runs script files only, and htmx runs without `allowEval`: no inline handler, `hx-on`, `js:` value, or trigger filter. A renderer marks its element (`data-post-event`, `data-close-dialog`, ...) or triggers on a custom event (`enter-key`, `escape-key`, `activate`), and the page's scripts do the rest (see [The page's scripts](#the-pages-scripts)). - **Hidden fragments keep their id.** A hidden fragment's root keeps its id (`hidden` attribute), so a later swap has a target. - **Updates.** When a rendered attribute changes, the renderer can mark itself dirty. `collect_dirty` records dirty renderers during a request or a handover from a worker thread. `render_dirty` returns out-of-band (OOB) swaps for their fragments that are in the page, even if they are hidden. It omits a fragment if another swap already includes it. `hx-swap="none"` prevents the normal swap, but an OOB swap can still replace the sender. A text field handles a user edit inside `stop_refresh()` to avoid replacing the field while the user types. If the user leaves a numeric field with text that does not parse, the renderer marks the field dirty so the response restores the view's value. - **Changes from threads.** `call_on_main_thread` runs its callback under the session's lock, and keeps what it changed in the session's `pending`. They are sent with the next event's response or fetch (a full page drops them). While the main view's jobs run, the page's `cui-jobs` poller fetches `/_composeui/jobs` every `JOBS_POLL_MS`, which brings them. The server pushes nothing, so an idle page sends nothing. A response whose event starts or ends the jobs swaps the poller in, as it does the page's marker. - **Repeating tasks.** Between two runs of a task with `every`, no job runs. One thread of the process (`_Timer` in `core/jobs.py`) keeps the next runs of every session in a heap, by the time they are due, and posts each one to its session. The post runs in a short thread of its own, as it waits for the session's lock, which a long request can hold: the other sessions' runs don't wait behind it. While a task only waits, the poller fetches once each `every` (`jobs_poll_delay`), not every `JOBS_POLL_MS`. A session that only waits for a task's next run can hibernate: the timer isn't in its saved state, but waking opens the study again, which emits `loaded`, and the app's callback starts the task again. A session that ends or hibernates leaves its next run in the timer: the run's post finds the session ended (`has_ended`) and starts nothing. - **Choices of several values.** Each box of a check list posts its key and its state, not a flip, and the check-all box posts its state too. A post that arrives twice leaves the same choice, and a click on a stale page does what the page showed. The user's change swaps only the parts that it changes: the check-all box, the list, and a multi-combobox's summary. It never swaps the box clicked or the search field, which keep the focus. A post that changes nothing, such as one of a stale page, swaps all three back as the view is. The check-all box shows partly checked through `tables.js`, which reads `data-indeterminate`. - **A drop-down list swapped while open.** When the app updates a multi-combobox, the response replaces the entire control. Each box has an id made from its key, so htmx gives it the focus back. But the dropdown is open only while the focus is in it, and a closed one's boxes take no focus. So `page.js` keeps it open through the swap with `dropdown-open`, on the element swapped out too: htmx gives the new element the old one's classes until it settles. - **Ranges.** A range slider stacks two range inputs on one track, only their handles taking the pointer. The lower input draws the track and the fill between the handles, from the handles' positions (`--range-low`, `--range-high`), as daisyUI's fill only reaches one handle. The inputs count steps, so a decimal step needs no decimal arithmetic in the page. Each posts both positions, as the page shows them, and the server takes them by `RangeSliderMixin.moved`. While dragged, `page.js` stops a handle on the other. When the two meet in the upper half of the track, the low one goes on top (`data-low-on-top`): the high one can't move below it, so a press there moves the low one down. A date range is two date fields, each posting its end. The end that followed the one set swaps alone, never the field typed in. ## The page's scripts - **One script per domain.** The scripts are files of `webcore/static/`, in the hashed addresses of `page.py`: - `page.js` runs in the `
`. It applies the theme before the body paints, and holds the common controls, the request and session headers, the post numbers, the protection against stale fragments, the loading of the libraries, and the `MutationObserver` that runs each script's work after a change of the page. - `tables.js` runs once after `page.js`, before the body: row activation, cell editing, the check-all box, a large table's scroll windows, and its clipboard. - `charts.js` loads with uPlot, `maps.js` with deck.gl, and `meshes.js` with vtk.js, once the page shows the first chart, map or mesh. - **Classic scripts, no bundler.** Each script keeps its code in a closure, and shares only what the others use, under `window.ComposeUI`: `dispatch` from `page.js`, and the `sync` functions of `charts.js`, `maps.js` and `meshes.js`, which they add once loaded. `page.js` calls them from its observer. - **The library, then the script.** `page.js` loads uPlot, then `charts.js` (deck.gl, then `maps.js`; vtk.js, then `meshes.js`), one after the other. A failed load is forgotten, and asked again on a later change of the page, up to five times: never as the other file arrives. Once both are there, each change of the page goes to the script before any check that a chart is shown, so a chart swapped out is destroyed, and a map finalized. - **A chart's bars.** The server places the bars: the JSON of a chart holds each bar series' offset and width (`ChartView.bar_slots`), and the room between two bars' x. A series of another kind takes no room, so a line stands at the categories, over the bars. Without categories, `charts.js` adds half of that room to each end of the x range, so that the first and the last bar show whole. It adds it only when the range is the whole data: uPlot runs a scale's range function on a zoom too, and a zoom widened at each draw would drift as the series change. - **A chart's stacked bars.** The server sends each stacked bar series its bars' bases (`ChartView.stack_bases`), by the points it sends, and each y axis how far its stacks reach, which its range takes in: uPlot fits a series' own values, which the legend keeps. The bars' builder draws each from its base (its `y0` and `y1` facets), and the hover shows no dot on a stacked bar, which would stand at the series' own value. Textual's plotext has no base: each bar goes from 0 to where it ends, the stack's last series first, which the others then cover. - **A chart's horizontal bars.** `charts.js` turns the x scale upright (uPlot's `ori: 1`, with `dir: -1` for the first category at the top) and the y scale along the bottom, and puts their axes at the left and the bottom. uPlot's bars' builder then draws the bars along the y, from the same facets. uPlot gives a left axis a fixed width: `fittedAxisSize` measures its widest value, so that a category's name shows whole. A click posts the pointer's height as the x and its left offset as the y. The rest of `charts.js` names the scales as before: the x range, the zoom kept across a swap, and the image's address stay those of the x. - **A chart's bounds.** `charts.js` wraps each scale's range function last, so that an axis' bounds (`Axis.minimum`, `Axis.maximum`) win over the bars' 0 and the reference lines. The x range keeps a zoom as the user made it, which uPlot also asks the range function for. The zoom kept across a swap, and the image's address, take the whole data at the bounds for no zoom. - **A chart's times.** A time axis' values are seconds since 1970, in UTC, on every backend. The page shows them in UTC whatever the browser's time zone: uPlot's `tzDate` and the legend read them as `Etc/UTC`. So a naive `datetime`, which the core takes as UTC, shows as the app wrote it, as Qt (`DateAxisItem(utcOffset=0)`), Textual and matplotlib show it. The server sends how precise the times are (`time`: `day`, `minute` or `second`), which the legend shows. - **A text editor's Copy all and Save.** `page.js` copies the `