Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,17 +10,19 @@ WebFront is a C++23 header-only library for serving a browser UI from a C++ appl

WebFront also ships a standalone developer environment (`NativeApp::bootstrap("developer")`): a terminal whose `wf` commands (`init`, `create`, `install`, `restore`, `run`, `exec`, `check`, `test`, `build`, `dev`, `preview`, `embed`, `list`, `help`) manage a project manifest and lock, compile TS/TSX, type-check, run Jasmine specs and generate the application's embedded provider, with no JavaScript runtime or package manager on the developer's machine. It is not a sandbox. See `docs/DEVELOPER_ENVIRONMENT.md`.

The README introduces WebFront through the Game of Life walkthrough, demonstrating the developer bootstrap, reactive TypeScript UI and embedded distribution. The minimal `HelloWorld` example remains available under `examples/hello-world/`. Native modules and the bridge are covered by the Jasmine browser integration test. The optional `ui.document()` API provides per-connection DOM islands, batched writes, events and grouped sender reads; see `docs/DOM.md`. Application coroutines use `webfront::Task` and `app.spawn(task)`/`ui.spawn(task)`; retain a `TaskHandle` to request individual cancellation. WebFront owns and drains these tasks. Spawn is callable from any thread while the application lives; a call rejected during shutdown returns a stopped handle. Destructors wait for outstanding operations; explicit shutdown reports a stalled join. Typed C++ sender calls support local cancellation; futures and JavaScript Promises do not expose cancellation.
The README introduces WebFront through the Game of Life walkthrough, demonstrating the developer bootstrap, reactive TypeScript UI and embedded distribution. The minimal `HelloWorld` example remains available under `examples/hello-world/`. Native modules and the bridge are covered by the Jasmine browser integration test. The optional `ui.document()` API provides per-connection DOM islands, batched writes, events and grouped sender reads; see `docs/DOM.md`. The optional React store and `Island` adapter, including its support policy and coordinated unmount contract, is described in `docs/REACT.md`; `examples/life/react/` demonstrates it. Application coroutines use `webfront::Task` and `app.spawn(task)`/`ui.spawn(task)`; retain a `TaskHandle` to request individual cancellation. WebFront owns and drains these tasks. Spawn is callable from any thread while the application lives; a call rejected during shutdown returns a stopped handle. Destructors wait for outstanding operations; explicit shutdown reports a stalled join. Typed C++ sender calls support local cancellation; futures and JavaScript Promises do not expose cancellation.

## Repository map

- `include/webfront/`: public header-only library, included as `<webfront/...>`. `WebFront.hpp` is the main orchestration API; `Commands.hpp` adds an application's C++ commands to the developer environment's terminal.
- `include/webfront/components/react/`: optional C++ snapshot stores coalesced per browser; the React adapter is installed separately with `wf` and documented in `docs/REACT.md`.
- `include/webfront/http/`: HTTP and WebSocket protocol implementation.
- `include/webfront/weblink/`: bridge message encoding and routing.
- `include/webfront/system/`: layered virtual filesystems and the embedded web resources, a closed list guarded by the `MinimalCoreAssets` CTest case (normative list and 150 KiB decoded budget in ADR-016; changing it means amending the ADR and `test/cmake/CheckMinimalCoreAssets.cmake` together).
- `include/webfront/frontend/`: system-browser, CEF, optional Windows WebView2 and macOS WKWebView frontend adapters.
- `examples/`: only Hello World (`hello-world/`) and Game of Life (`life/`, with console, developer and embedded stages).
- `examples/`: only Hello World (`hello-world/`) and Game of Life (`life/`, with console, developer and embedded stages, plus the `life/react/` variant with a C++ panel inside React).
- `js/core/`: readable browser bridge, fallback and bootstrap loader compiled into `include/webfront/`, plus the embedding CMake modules; `js/developer/`: developer environment (its terminal and `wf`), the wf scripts that build it (`scripts/`), build and publication tools. The repository is itself a `wf` project (`js/developer/webfront.project.json` and its lock, selected with `--manifest-dir js/developer`): the environment builds itself, and its pure JavaScript specs (`test/developer/`) run with `wf test`. Production C++ remains header-only in `include/webfront/`.
- `js/react/`: optional `@webfront/react` package (`createStore`, `useStore`, `Island`), declarations and package-local license. `wf run react-package` assembles it; tests verify the exact archive installed by the registry. It is outside the core's embedded resource list.
- `test/fixtures/`, `test/web/fixtures/`: retained regression fixtures, not public example applications.
- `test/unit/`: Catch2 unit tests; `test/web/`: real-browser integration (`suite/` is the WebFront project of the Jasmine specs, run by `webtest` through `wf test`); `test/driver/`: `webfront-wf`, the non-interactive `wf` driver for tests; `test/fuzz/`, `test/fixtures/`; `test/cmake/`: CMake test scripts and sub-projects. The `RepositoryLayout` CTest case pins the tracked root.
- `cmake/`: build modules (frontends, CEF, CPM, compiler options); `.github/`: workflows, `.github/CONTRIBUTING.md`.
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -279,6 +279,7 @@ CI runs one combined C++ / native-browser job per desktop platform on each code
- JavaScript calls to C++ always return Promises. C++ `ui.jsFunction(name)(...)` is fire-and-forget; `ui.jsFunction<R>(name)(...)` returns `std::future<R>`. Missing functions, exceptions, malformed replies and disconnects fail the typed call.
- The binary bridge supports scalars, strings, tuples, numeric typed arrays and packed bitsets. Arbitrary objects do not cross it. Strings have a 16-bit encoded length limit.
- Development project access is explicit and intended for trusted local code. Downloaded tools run with the application's bridge authority, and script permissions frame only the `context` API: neither is a sandbox. Only packages that run in a browser are supported; installation scripts and native add-ons are not executed. Builds transform TypeScript without type checking; `wf check` type-checks with the compiler the project locks.
- The optional [`@webfront/react` adapter](docs/REACT.md) supplies coalesced C++ stores and empty React islands. `WebFrontLifeReact` demonstrates a C++ panel within the Game of Life React UI; its package archive is prepared locally for registry publication.
- Packaging, accessibility and native-engine deployment still need application-specific work. The optional [`ui.document()` API](docs/DOM.md) provides DOM islands, automatically batched writes, event callbacks and grouped sender reads. See [project status](docs/PROJECT_STATUS.md) for known limitations.

## License
Expand Down
13 changes: 13 additions & 0 deletions docs/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,19 @@

## Unreleased

- Optional React adapter (#382): an installable `@webfront/react` package with cached
`useSyncExternalStore` snapshots and empty `Island` components that tolerate StrictMode
effect replay. `webfront::react::Store` coalesces the last snapshot per 1 ms server cycle
without changing the wire format or core assets. A Game of Life variant constructs its
simulation panel in C++ inside React. Package assembly, wf installation, declarations,
batching and island lifecycle have regression coverage. Explicit flush failures retain the
pending snapshot; automatic error callbacks are contained and logged. Moved-from
store wrappers reject operations explicitly. Self-capturing error callbacks are released on
close and automatic failure; subscriber and island-release exceptions are logged and isolated.
The Life variant gates
cell edits until startup succeeds and bounds island readiness. Test installation uses the exact
archive bytes, with file-list and SHA-512 checks. Registry publication stays explicit.

- License WebFront under Apache-2.0 OR CECILL-B, at the recipient's option.
Include both full license texts (CeCILL-B in French and English), document
contribution terms and carry the license into newly built developer and
Expand Down
3 changes: 3 additions & 0 deletions docs/DOM.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@ app.onUIStarted([](auto ui) {
});
```

The optional [`@webfront/react` adapter](REACT.md) lends empty React `Island` components
and provides coalesced C++ stores; it is installed separately with `wf`.

A custom page lends only empty, disjoint elements that its UI library does not
reconcile. It opts into the document callbacks explicitly:

Expand Down
3 changes: 3 additions & 0 deletions docs/PROJECT_STATUS.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,5 +81,8 @@ are retained for investigation; diagnostics alone do not establish a correction.
[the wire contract](adr/ADR-003-protocole-binaire-et-bornes.md#commande-dom-dombatch-code-5-version-1).
The per-connection document/node API, events and grouped sender reads are available; see
[DOM from C++](DOM.md). A direct engine transport remains future work.
The optional [React adapter](REACT.md) provides a coalesced C++ store and a StrictMode-safe
`Island`, demonstrated in the Life variant. Its npm archive is prepared locally; public
registry publication is a separate action. Solid, Svelte, Vue and Lit adapters remain future work.
[ADR-018](adr/ADR-018-acces-au-dom.md) describes DOM islands;
[ADR-017](adr/ADR-017-acces-direct-aux-frontends.md) retains transport experiments and acceptance criteria.
164 changes: 164 additions & 0 deletions docs/REACT.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
# React stores and C++ islands

`@webfront/react` is an optional package, installed by `wf` from an npm-compatible
registry. Its sources and declarations live in `js/react`; it is not an embedded
core resource. React remains a peer dependency, shared with the application. `@types/react` is an
optional peer for TypeScript projects; install it explicitly alongside TypeScript.
No `react-reconciler` is used. The peer ranges are React `^19.3.1` and optional
`@types/react` `^19.3.0`; CI tests React 19.3.1 and `@types/react` 19.3.0. `useSyncExternalStore` reads cached snapshots;
development React 19.3.1 is exercised under `StrictMode`. This lower bound is a
support/qualification policy based on that CI baseline, not a technical requirement
of the hooks: the hooks used by the adapter exist in React 18, but React 18 and
19.0–19.2 have not been qualified here.

## Store

Install the browser receiver before asking C++ to send:

```tsx
import {createStore, useStore} from '@webfront/react';
const statistics = createStore<[number, string]>('statistics', [0, 'Waiting']);
function Statistics() {
const [count, label] = useStore(statistics);
return <p>{count}: {label}</p>;
}
```

In a server-context callback, construct and retain a store for that browser:

```cpp
#include <webfront/components/react/Store.hpp>
using Snapshot = std::tuple<std::uint32_t, std::string>;
webfront::react::Store<UI, Snapshot> statistics{ui, "statistics"};
statistics.set({1, "Running"});
statistics.set({2, "Running"}); // replaces the pending snapshot
```

Copies share pending state. Moving a store transfers its wrapper: the source's
`valid()` returns false, and `set`, `flush`, `close` and `onError` throw
`std::runtime_error` on that moved-from wrapper. The first `set` schedules an application-owned task,
which waits 1 ms on the server context. Only the last complete snapshot is sent.
A burst of 1,000 `set` calls in one callback produces one bridge message and one
React commit in the browser regression. This is a server cadence, not a rendering
deadline: writes in later cycles can cause additional commits. Different stores
have independent cycles; fields requiring an atomic update belong in one tuple.
`flush()` queues the latest snapshot early, without awaiting the browser.

`T` must be a supported bridge value: scalar, string, tuple, numeric typed array
or packed bitset. Tuples arrive as arrays. Ordinary JavaScript objects do not cross
the bridge. Snapshot identity is stable until a message arrives; treat snapshots,
including nested arrays and typed arrays, as immutable. Subscribe functions stay
stable and return an unsubscribe function. An identical snapshot by `Object.is`
does not notify. Store names contain ASCII letters, digits, `_` or `-`. The browser namespace
`webfrontReactStores` is reserved for these receivers. A throwing subscriber is
logged to the browser console and does not interrupt the remaining subscribers;
the adapter contains diagnostic logging failures too.

The C++ store shares its connection's document lifetime and thread rules, even
when no island is used. It does not require `dom.connect()` to send data. Create
and mutate it on the server context. Disconnect, document rejection and application
shutdown invalidate it; the timer is owned and drained by the application.
`valid()` returns false off that thread. Retained stores are safe to inspect after
the application has been destroyed; they do not extend the lifetime of `UI`.
`close()` discards pending values, releases the installed error callback and
invalidates all copies. Synchronous errors
from `set`/`flush` throw. An explicit `flush()` encoding/send failure retains the
pending snapshot and leaves the store open for retry (including the scheduled
cycle). Only a successful send clears that pending snapshot. An automatic
encoding/send failure closes the store and calls `onError(std::exception_ptr)` if
installed. The automatic failure consumes and clears that callback before invoking
it, so a callback capturing a store copy does not keep a closed store alive.
Self-owning callbacks still require an explicit `close()` on the normal path;
prefer weak captures when that lifecycle cannot be guaranteed.
Exceptions thrown by `onError` are caught and logged; they cannot escape
the automatic-send coroutine. Browser function failures are
not acknowledged by this untyped, fire-and-forget C++ call.

Create only one C++ store per browser/name and share its copies; two independently
constructed stores do not coalesce together. Browser `createStore` rejects duplicate
names. `dispose()` removes the receiver and subscribers; coordinate it with C++
`close()` after stopping writers. Store disposal is explicit, independent of a
component's StrictMode cleanup. Unmount all consumers before disposal: subscribing
to a disposed store throws, including a later `useSyncExternalStore` resubscription
while rendering a mounted consumer. Optional `{target: window}` installs a receiver
in another window; the default is `globalThis`.

## Island

Load the optional server interpreter and pass it to an empty component:

```tsx
import {Island} from '@webfront/react';
async function prepareDom() {
const interpreterUrl = '/webfront-dom.mjs';
const {installDomInterpreter} = await import(interpreterUrl);
return installDomInterpreter(webFront);
}
// After prepareDom() resolves, render inside your existing React tree:
// <Island dom={dom} name="panel" className="panel" />
```

`Island` renders a `div` without children. Its layout effect lends that element;
after the React commit, `await dom.connect()` and ask a C++ callback to build
`ui.document().island("panel")`. Never send mutations before the corresponding
island is committed. `children` and `dangerouslySetInnerHTML` are rejected at
runtime and excluded from its TypeScript props. Keep `name` and `dom` stable for
the mounted component. Each island name is unique within its interpreter.

StrictMode's immediate effect cleanup/setup replay keeps the same loan and C++
children. Release is deferred to a microtask; a real unmount revokes the loan.
Unexpected synchronous release errors are caught and logged, and the adapter drops
its local lease. Such an error still requires application-level recovery/reload;
logging it does not acknowledge a C++ revocation. A bridge already closed rejects
the interpreter's revocation Promise, which the interpreter handles and logs.
Parent renders preserve the C++ subtree. A later real mount gets fresh node IDs.
Delayed effect disconnect/reconnect mechanisms such as React
[`Activity`](https://react.dev/reference/react/Activity) or Offscreen are unsupported
for a live `Island`: hiding revokes its loan, and revealing preserved DOM does not
restore it. Coordinate a full unmount, fresh empty mount and C++ rebuild instead.
Unmount still requires the [document handoff](DOM.md#coordinating-page-unmounts):
pause all document writers, flush, await a browser round trip, then unmount and
await an application-level acknowledgement that C++ observed the revocation
before resuming. The release function itself returns no acknowledgement or Promise.
The component cannot pause application writers itself. An uncoordinated unmount can close the whole document.

## Game of Life variant

`examples/life/react/` keeps the simulation in C++, renders the grid and statistics
with React, and builds a heading, status and “Next generation” button in C++ inside `life-panel`.
The C++ event computes a generation, updates the island and sets a tuple snapshot
containing the packed grid, generation and population. Each browser owns a separate
simulation, released on disconnect. The original Life starter remains available.

Build the `WebFrontLifeReact` CMake target and run it with a writable copy of
`main.tsx` and `webfront.project.json` from that directory as its project argument.
In its terminal, run `wf install`, then `wf preview`. The configured registry must
carry `@webfront/react@0.1.0`; this change prepares the archive but does not publish
to npm. The repository's test registry already carries the package. For a local
evaluation, configure the driver with `--registry-dir <build>/test/web/self-build-project/build-registry`;
the browser suite uses that registry for this adapter and React. To use the same
registry in `WebFrontLifeReact`, copy its contents to `<project>/registry/` and add
`"registry": "/registry/"` to the project manifest before `wf install`. This is a
development mirror served from the project document root.

To prepare the archive, use the repository wf project after restoring its packages:

```sh
wf run react-package
```

This writes `build-react-package/webfront-react-0.1.0.tgz` and `integrity.txt`.
Publishing that archive to a registry is a separate maintainer action.

The test registry uses the same deterministic packager as `wf run react-package`.
`ReactAdapterPackageContents` verifies byte-for-byte archive equality, the exact
file list, every maintained source file and the SHA-512 in `integrity.txt`.
The Life canvas ignores clicks until `life.react.start` acknowledges startup. If
the React island does not mount within five seconds, startup fails visibly.
Editing a cell starts a new simulation at generation zero.

The generated `.tgz` uses valid gzip stored blocks, without size compression, so
bootstrap packaging needs no preinstalled compressor. Registry publication is a
separate step and may retain this format or recompress with a newly recorded digest.
The canvas cell editor is pointer-only; the C++ “Next generation” button supports
normal keyboard activation. A complete keyboard cell editor is not demonstrated.
Loading
Loading