diff --git a/craft/blueprints/codebases/dart/a2ui_craft/codebase.blueprint.md b/craft/blueprints/codebases/dart/a2ui_craft/codebase.blueprint.md index 434fca5d..b7e96dd3 100644 --- a/craft/blueprints/codebases/dart/a2ui_craft/codebase.blueprint.md +++ b/craft/blueprints/codebases/dart/a2ui_craft/codebase.blueprint.md @@ -30,16 +30,19 @@ The Dart implementation of the framework-independent part of the Craft engine (` - **Binary format**: `lib/src/rfw/binary.dart`, forked from RFW 2.0.0 like the text format. It writes the Craft signatures, version header and declaration flags, decodes RFW blobs as version 0, skips extension values, and reports every decoding error as a `BlobFormatException` with a `BlobErrorKind` and a byte offset. - **Name resolution**: `lib/src/name_resolution.dart`. `NameResolver` applies the `craft_libraries_and_names` rules over a live map of registered libraries (template libraries and `PrimitiveLibrary` implementations provided by framework adapters) and caches results until `invalidate`. - **Functions**: `lib/src/functions.dart` defines a function (`LocalFunction`: parameters with a `FunctionArgType` and an implementation), the `FunctionRegistry` of standard and host functions, which checks host keys, and the value helpers the functions share (equality, exact number comparison, number display). `lib/src/standard_functions.dart` holds the standard functions. `lib/src/evaluator.dart` evaluates the values that need no runtime (literals, lists, maps, `absent`, args/data/state references, function calls), tells function calls from widget calls with `NameResolver`, and reports every failure as an `EvaluationException` with an `EvaluationErrorKind`. -- **Template registry**: `lib/src/template_registry.dart`. `TemplateRegistry` holds the registered template and primitive libraries (primitive libraries as a copy of their names and metadata) and the host functions, owns the `NameResolver` over them, builds each library's function table (standard functions, the introspection functions answering for that library, host functions), reads symbol references through the evaluator's `SymbolReader`, and computes the availability of libraries and components as a fixed point. Every registration drops the derived results. `lib/src/dependencies.dart` holds the declared dependencies (`LibraryDependencies`, `Requirement`) and the availability reports. -- **Runtime**: `lib/src/expansion.dart` defines the expansion: primitive, error and builder nodes, the handler nodes (`EventValue`, `SetStateValue`, `HandlerCallValue`, `HostHandler`), stateful instances, and the canonical JSON form. `lib/src/runtime.dart` holds `CraftRuntime`, which expands a root over a `TemplateRegistry`, keeps the state of its instances (reset when the registry's generation of the declaring library changes, so also when the same object is registered again; `TemplateRegistry.generation` counts each name's registrations and removals), expands builder outputs, fires handlers and notifies listeners. A failure records the scope and the source range of the innermost node it passes through (each evaluation, and a primitive call while its arguments evaluate), which become the `template` and `source` of the `ErrorNode`. Evaluation happens in two phases: a node evaluates in a scope to a value or to a widget call not yet expanded (template arguments are evaluated on first read and kept), and placing that value at a path expands its widget calls, catching failures at the innermost widget. It calls functions through `checkCallArguments` and `invokeFunction`, shared with `lib/src/evaluator.dart`. The whole tree is expanded again after every change; there is no fine-grained invalidation. +- **Template registry**: `lib/src/template_registry.dart`. `TemplateRegistry` holds the registered template and primitive libraries (primitive libraries as a copy of their names and metadata) and the host functions, owns the `NameResolver` over them, builds each library's function table (standard functions, the introspection functions answering for that library, host functions), reads symbol references through the evaluator's `SymbolReader`, and computes the availability of libraries and components as a fixed point. Every registration drops the derived results and then calls the registry's listeners. `lib/src/dependencies.dart` holds the declared dependencies (`LibraryDependencies`, `Requirement`) and the availability reports. +- **Runtime**: `lib/src/expansion.dart` defines the expansion: primitive, error and builder nodes, the handler nodes (`EventValue`, `SetStateValue`, `HandlerCallValue`, `HostHandler`), stateful instances, and the canonical JSON form. `lib/src/runtime.dart` holds `CraftRuntime`, which expands a root over a `TemplateRegistry`, keeps the state of its instances (reset when the registry's generation of the declaring library changes, so also when the same object is registered again; `TemplateRegistry.generation` counts each name's registrations and removals; `refresh` drops such instances at once, the next expansion otherwise), expands builder outputs, fires handlers and notifies listeners. A failure records the scope and the source range of the innermost node it passes through (each evaluation, and a primitive call while its arguments evaluate), which become the `template` and `source` of the `ErrorNode`. Evaluation happens in two phases: a node evaluates in a scope to a value or to a widget call not yet expanded (template arguments are evaluated on first read and kept), and placing that value at a path expands its widget calls, catching failures at the innermost widget. It calls functions through `checkCallArguments` and `invokeFunction`, shared with `lib/src/evaluator.dart`. The whole tree is expanded again after every change; there is no fine-grained invalidation. - **A2UI integration**: the framework-independent part of `craft_a2ui_integration` (requirements 1 to 6; requirement 7, rendering, is implemented for Flutter by `a2ui_craft_renderer_flutter`). `lib/src/a2ui_catalog.dart` derives each offered component's `TemplateInterface` (its properties with their `ArgKind`, and whether it is checkable) by walking its declaration's root with the kind of each position, following template calls with a per-declaration cache that skips results computed through a call back into a declaration under analysis, and writes the A2UI v1.0 component schema (`templateCatalogSchemas`). `lib/src/a2ui_props.dart` maps resolved props, described with `A2uiProp` (each holding the renderer's own object, which this package never looks into), to `TemplateArgs`: the arguments with their host handlers and host widgets, and the `A2uiEffect`s of each event that firing gives. `TemplateRegistry.primitiveMeta` gives the analysis the metadata of a primitive. The runtime carries host widgets (`HostWidget`, placed as `HostWidgetNode`s) for the renderer's child nodes. - **Media context**: `lib/src/media_context.dart` defines `MediaContext` (made from its properties or with `MediaContext.fromSize`, whose breakpoints are in `WidthClass.of` and `HeightClass.of`), `SurfaceOrientation` and `HostPlatform`, the media map (`toMap`), `readMedia`, which both the evaluator and the runtime use for media references, and `mediaFunctions` (`atLeast`), which `TemplateRegistry.functionsFor` adds to every function table next to the standard and introspection functions. `Evaluator.evaluate` and `TemplateRegistry.evaluate` take a media context; `CraftRuntime.media` holds the runtime's; its setter notifies only when the new one is not equal, and `setMedia(notify: false)` replaces it without notifying, for a host that calls `refresh` later. - **Limits**: `lib/src/limits.dart` defines `CraftLimits` (the six limits, their defaults and JSON form), `CraftLimitException`, `checkLibraryLimits` (the declaration measures, which `TemplateRegistry.setTemplateLibrary` applies) and `limitedValue` (the conversion of host values and function results with the depth and string checks, which fails at a `BeyondLimits` marker; `TemplateArgs.from` puts one in place of a prop value beyond the limits). The parser (`lib/src/rfw/text.dart`) counts the depth and nodes of the library it builds as it reads, keeping each `let` binding's depth and node count to add them at each use, and reports a `ParserException` with a `limit`; the decoder (`lib/src/rfw/binary.dart`) counts tagged values and reports `BlobErrorKind.limitExceeded`. The evaluator and the runtime count the depth of the node being evaluated; the runtime's pass also counts steps and nodes, throws a private stop exception past either budget (never cached by a template argument), and gives back the instances it had before the pass. - **Canonical JSON form**: `lib/src/canonical_json.dart`, used by the conformance harness. +- **Public libraries**: `lib/a2ui_craft.dart` exports everything a host uses. Of the library model it exports a library's structure (`RemoteWidgetLibrary`, `WidgetLibrary`, `Import`, `WidgetDeclaration`, `BlobNode`) and every other model type that its API names (`LibraryName`, `FullyQualifiedWidgetName`, `Missing` and `missing`, `DynamicMap`, `DynamicList`, `SourceLocation`, `SourceRange`, `SymbolReference`); `test/public_api_test.dart` names each of them through that import alone. The other nodes of a declaration's body (`Switch`, `Loop`, `ConstructorCall`, references, handlers, builders) are in `lib/model.dart`, for tools and tests that inspect or build libraries. `checkCallArguments`, shared by the evaluator and the runtime, is not exported. - **Conformance harness** (`dart-craft`): `test/conformance/conformance_harness.dart` loads each suite of `conformance/craft/`, runs every case with the handler of its `action` (handlers shared by several suites are in `parse_cases.dart`, `resolution_cases.dart` and `runtime_engine.dart`), fails a case with an unknown action or key, and writes an executed-case manifest when `A2UI_CONFORMANCE_MANIFEST_DIR` is set. `suite_registry.dart` names the test file of each suite. ## **Local Technical Decisions & Overrides** +- **Library model in its own library**: a host file usually imports `package:material_ui/material_ui.dart` too, whose `Switch` widget would clash with the model's `Switch` node; keeping the nodes out of the main library lets both be imported without `hide`. +- **Registry notifications without Flutter**: `TemplateRegistry.addListener` takes plain callbacks, as `CraftRuntime` does, so the package keeps no Flutter dependency; a listener that throws goes to `onListenerError`, by default to the zone's uncaught error handler (Flutter reports those), rather than out of the registration that already took effect; a runtime does not listen to its registry itself (it would need disposing), the adapter tells it with `refresh`. - **Depth ceiling**: `CraftLimits` refuses a `maxDepth` above 1,000 (`CraftLimits.maxDepthCeiling`). At 2,000 a chain of templates overflowed the stack of a desktop VM; the default, 100, leaves a margin for smaller stacks. - **Encoders are not limited**: `encodeLibraryBlob` and `encodeDataBlob` write what the host gives them, so a library or value that the host builds deeper than the stack allows overflows there; everything the parser, decoders and registry accept encodes. - **Numbers on the web**: compiled with dart2js, every number is a JavaScript number (a double), and a whole one is also an `int`, so integers and doubles cannot be told apart and integers are exact only up to 2^53 in magnitude. There the standard functions follow the double rules of `craft_functions` wherever they differ from the integer rules: `add`, `subtract` and `multiply` give absent only for a result that is not finite, `round`, `floor` and `ceil` give absent outside the 64-bit range, `abs` never gives absent, a number displays as a double does, and comparisons compare the doubles, which is exact. The canonical JSON form gives every whole number the integer form, so the conformance cases that tell integers from doubles or need integers beyond 2^53 are skipped there (`test/conformance/js_skips.dart`). Compiled with dart2wasm, numbers behave as on the VM. diff --git a/craft/blueprints/codebases/dart/a2ui_craft_flutter/codebase.blueprint.md b/craft/blueprints/codebases/dart/a2ui_craft_flutter/codebase.blueprint.md index 5a6e9f22..81d85489 100644 --- a/craft/blueprints/codebases/dart/a2ui_craft_flutter/codebase.blueprint.md +++ b/craft/blueprints/codebases/dart/a2ui_craft_flutter/codebase.blueprint.md @@ -16,17 +16,17 @@ local_development: The Flutter adapter of the Craft engine (`a2ui_craft_flutter`). The `craft_runtime` feature is implemented by `a2ui_craft` (`CraftRuntime`), which produces the expansion; this package only renders it with Flutter widgets, so it claims no feature of its own. Building blocks are not part of it: a host supplies its primitives as Flutter widgets. - **Primitives**: `lib/src/primitive_widgets.dart`. A `PrimitiveWidgetLibrary` maps primitive names to `PrimitiveWidget`s (a builder and the metadata templates read). It is a `PrimitiveLibrary`, so the host registers the same object in the `TemplateRegistry` and gives it to `CraftView`. A builder reads its node through `PrimitiveArguments`: values, `child` and `children` (widget, host widget and error nodes; other elements, such as absent ones, are no child), `handler` and `valueHandler` (null when the handler is not runnable, so the control can be disabled; a value handler fires with `{value: v}`), and `builder` (expands a builder's output for a key and an argument). -- **View**: `lib/src/craft_view.dart`. `CraftView` renders the current expansion of a `CraftRuntime` and expands it again when the runtime notifies a change; changes notified while a frame is being built are rendered by one expansion after that frame, so no rebuild is requested during a build. It stops listening when it is disposed. Firing goes to the runtime; the events it gives go to `onEvent`. Expansion errors (of the root and of builder outputs), firing errors and primitives without a widget (`MissingPrimitiveWidget`) go to `onError` after the frame that renders them, unless the view is gone by then; an error found while rendering is reported once per expansion of the root, however often it is rebuilt; and error nodes render as a small `ErrorWidget` unless `errorBuilder` says otherwise. Host widget nodes render what `hostWidgetBuilder` builds for them, or nothing without it. -- **Media context**: also in `lib/src/craft_view.dart`. `CraftView.media` (a `MediaSource`) says where the runtime's media context comes from: `layout` (the default) measures the maximum size of the view's layout constraints with a `LayoutBuilder`, taking the `MediaQuery` size for an unbounded axis; `window` takes the `MediaQuery` size; `host` leaves the media context to the host. In the first two the view sets the media context with `MediaContext.fromSize`, the platform from `defaultTargetPlatform` (`web` on the web) and `reducedMotion` from `MediaQuery.disableAnimations`, before it expands, so the first frame and the frame of a resize across a class render the new classes, with one expansion each; a resize within the same classes expands nothing. It sets the media context without notifying (`CraftRuntime.setMedia(notify: false)`), because that happens during build or layout, where a listening host must not rebuild, and calls `refresh` after the frame so that the runtime's other listeners hear of it; it ignores that notification itself. +- **View**: `lib/src/craft_view.dart`. `CraftView` renders the current expansion of a `CraftRuntime` and expands it again when the runtime notifies a change; changes notified while a frame is being built are rendered by one expansion after that frame, so no rebuild is requested during a build. It also listens to the runtime's `TemplateRegistry` and calls `CraftRuntime.refresh` when it changes, so the templates on screen follow new registrations in the next frame, the state of a library registered again dropped at once; it stops listening to both when it is disposed. Firing goes to the runtime; the events it gives go to `onEvent`. Expansion errors (of the root and of builder outputs), firing errors and primitives without a widget (`MissingPrimitiveWidget`) go to `onError` after the frame that renders them, unless the view is gone by then; an error found while rendering is reported once per expansion of the root, however often it is rebuilt; and error nodes render as a small `ErrorWidget` unless `errorBuilder` says otherwise. An expansion's errors (and the rendering errors found in it) that are still pending when a later expansion replaces it in the same frame are not reported: nothing showed them. Host widget nodes render what `hostWidgetBuilder` builds for them, or nothing without it. +- **Media context**: also in `lib/src/craft_view.dart`. `CraftView.media` (a `MediaSource`) says where the runtime's media context comes from: `layout` (the default) measures the maximum size of the view's layout constraints with a `SpaceBuilder` (`lib/src/space_builder.dart`, not exported), taking the `MediaQuery` size for an unbounded axis; `window` takes the `MediaQuery` size; `host` leaves the media context to the host. In the first two the view sets the media context with `MediaContext.fromSize`, the platform from `defaultTargetPlatform` (`web` on the web) and `reducedMotion` from `MediaQuery.disableAnimations`, before it expands, so the first frame and the frame of a resize across a class render the new classes; a resize across a class expands once, and one within the same classes expands nothing. In `layout` mode the first frame expands once for the `MediaQuery` size in the build phase (unless the runtime already has a media context, which it keeps), and once more in layout if the space has other classes. It sets the media context without notifying (`CraftRuntime.setMedia(notify: false)`), because that happens during build or layout, where a listening host must not rebuild, and calls `refresh` after the frame so that the runtime's other listeners hear of it; it ignores that notification itself. ## **Local Technical Decisions & Overrides** - **Whole-tree rendering**: every change renders the whole expansion again and leaves the diffing to Flutter; there is no per-node subscription as in RFW. -- **Media from the layout by default**: a template is often placed in part of the screen (an A2UI component in a row, a pane), and adapts to the space it actually gets. The cost is that of every `LayoutBuilder`: the view cannot answer intrinsic size queries in `layout` mode, which is why `window` and `host` exist. Two views that set the media context of one runtime from different sizes would keep replacing each other's; a runtime is shown by one such view. +- **Media from the layout by default, with intrinsic sizes**: a template is often placed in part of the screen (an A2UI component in a row, a pane), and adapts to the space it actually gets. A `LayoutBuilder` builds only during layout, so it cannot answer intrinsic size queries, and a template inside `IntrinsicWidth`, `IntrinsicHeight`, a dialog or a table would fail. `SpaceBuilder` builds like a `LayoutBuilder` (descendants rebuild in its own build scope, during its layout), and also in the build phase for the space of its last layout, or before the first layout for the window's size; it answers intrinsic queries with that child and builds again in layout only when the space changed. Intrinsic sizes and dry layouts are those of the child as last built, whatever the constraints asked about. So in an intrinsic context the template is first measured as rendered for the window's size (or its last space) and then rendered for the space the parent gives it. When that space has other classes and the template renders differently there, the ancestor keeps the size it measured: the rebuild happens during the ancestor's own layout, so its cached intrinsic size is not invalidated, and the layout does not converge to the rebuilt child's intrinsic size until something else lays the ancestor out again. A template whose content changes across that boundary can therefore get a box sized for its window-size layout. The first frame may also cost a second expansion. Two views that set the media context of one runtime from different sizes would keep replacing each other's; a runtime is shown by one such view. - **State lives in the runtime**: template state belongs to `CraftRuntime` instances keyed by path, not to Flutter `State` objects, so the same expansion renders identically in any adapter. ## **Validation & Execution Recipes** -- **Test execution**: `flutter test` runs widget tests with a small test-only primitive library (column, row, text, button, field and list widgets), checking that the view renders the expansion and host widgets, fires handlers, forwards events and errors, follows data updates and state, builds builder outputs, never rebuilds during a build, expands once for several changes during a build, stops listening when disposed, reports nothing once gone, and reports a rendering error once per expansion; and that each media source sets the media context (sizes, an unbounded axis, platform and reduced motion), renders a resize across a class in the same frame with one expansion, expands nothing for a resize within a class, reports no error from an expansion without a media context, notifies a listening host that rebuilds only after the frame, and answers intrinsic size queries in `window` and `host` modes. +- **Test execution**: `flutter test` runs widget tests with a small test-only primitive library (column, row, text, button, field and list widgets), checking that the view renders the expansion and host widgets, fires handlers, forwards events and errors, follows data updates and state, builds builder outputs, never rebuilds during a build, expands once for several changes during a build, stops listening when disposed, reports nothing once gone, and reports a rendering error once per expansion; and that each media source sets the media context (sizes, an unbounded axis, platform and reduced motion), renders a resize across a class in the same frame with one expansion, expands nothing for a resize within a class, reports no error from an expansion without a media context, notifies a listening host that rebuilds only after the frame, answers intrinsic size queries (`IntrinsicWidth` and `IntrinsicHeight`, sized to the text and not 0 px, and the view's min and max intrinsic widths and heights and dry layout) in every mode, keeps a runtime's media context in a new view, and drops the errors of an expansion replaced in the same frame; that a registration renders the view again until it is gone; and that the public library imports next to the Material and Cupertino libraries (`package:material_ui` and `package:cupertino_ui`) without hiding names (`test/imports_test.dart`). - **Static analysis**: `dart analyze --fatal-infos`. - **Formatting**: `dart format .`. diff --git a/craft/blueprints/codebases/dart/a2ui_craft_renderer_flutter/codebase.blueprint.md b/craft/blueprints/codebases/dart/a2ui_craft_renderer_flutter/codebase.blueprint.md index 1a8163d8..b5a48c61 100644 --- a/craft/blueprints/codebases/dart/a2ui_craft_renderer_flutter/codebase.blueprint.md +++ b/craft/blueprints/codebases/dart/a2ui_craft_renderer_flutter/codebase.blueprint.md @@ -15,7 +15,7 @@ local_development: Craft templates as catalog components of the A2UI Flutter renderer (`a2ui_craft_renderer_flutter`). It depends on the published `a2ui_core` and `a2ui_flutter` packages, uses only their public API, and changes neither. `a2ui_craft` claims the `craft_a2ui_integration` feature and implements its framework-independent parts (schemas, props to arguments, effects); this package implements requirement 7, rendering on top of them with `a2ui_craft_flutter`, so like that adapter it claims no feature of its own. -- **Catalog**: `lib/src/template_catalog.dart`. `templateCatalog` makes a v1.0 `CatalogImplementation` with one `ComponentImplementation` per offered component of a template library, its schema from `TemplateInterface.schema`, and the functions the host passes (for dynamic values and `@checks` on these components). Each node renders a stateful widget that keeps one `CraftRuntime` while the node lives and renders it with `CraftView`. On every rebuild it converts the node's props (`WritableBinding`, `ResolvedBinding`, `NodeAction`, child nodes, check results) into `A2uiProp`s, maps them to `TemplateArgs`, and replaces the runtime's arguments when their canonical form changed. Host widget nodes render the child node they stand for through the renderer's child builder. Effects go to `SurfaceModel.dispatchAction` from the node's component id, to the `NodeAction` invoked synchronously, or to `WritableBinding.set`. Errors go to `onError` with the component id. +- **Catalog**: `lib/src/template_catalog.dart`. `templateCatalog` makes a v1.0 `CatalogImplementation` with one `ComponentImplementation` per offered component of a template library, its schema from `TemplateInterface.schema`, and the functions the host passes (for dynamic values and `@checks` on these components). Each node renders a stateful widget that keeps one `CraftRuntime` while the node lives and renders it with `CraftView`, with the catalog's `media` source (by default `MediaSource.layout`, which also works inside intrinsic-size widgets) and `errorBuilder` for the placeholder of a failed widget. Because `CraftView` refreshes its runtime when the registry changes, components on screen render a library registered again in the next frame, with fresh state; the catalog's component list and schemas stay those it was made with. On every rebuild it converts the node's props (`WritableBinding`, `ResolvedBinding`, `NodeAction`, child nodes, check results) into `A2uiProp`s, maps them to `TemplateArgs`, and replaces the runtime's arguments when their canonical form changed. Host widget nodes render the child node they stand for through the renderer's child builder. Effects go to `SurfaceModel.dispatchAction` from the node's component id, to the `NodeAction` invoked synchronously, or to `WritableBinding.set`. Errors go to `onError` with the component id. ## **Local Technical Decisions & Overrides** @@ -25,6 +25,6 @@ Craft templates as catalog components of the A2UI Flutter renderer (`a2ui_craft_ ## **Validation & Execution Recipes** -- **Test execution**: `flutter test` runs widget tests that drive an A2UI surface with v1.0 messages through a `MessageProcessor` with strict validation, over the template catalog and the basic catalog, with test-only primitives. +- **Test execution**: `flutter test` runs widget tests that drive an A2UI surface with v1.0 messages through a `MessageProcessor` with strict validation, over the template catalog and the basic catalog, with test-only primitives, including the media class a component sees with each media source of the catalog, components inside `IntrinsicWidth` and `IntrinsicHeight` with each media source (sized to their content, not 0 px), a library registered again while on screen (new version rendered in the next frame, and the first tap after it counted) and a host's error placeholder. - **Static analysis**: `dart analyze --fatal-infos`. - **Formatting**: `dart format .`. diff --git a/craft/blueprints/features/craft_a2ui_integration.blueprint.md b/craft/blueprints/features/craft_a2ui_integration.blueprint.md index c39f7734..dc725a53 100644 --- a/craft/blueprints/features/craft_a2ui_integration.blueprint.md +++ b/craft/blueprints/features/craft_a2ui_integration.blueprint.md @@ -95,7 +95,8 @@ A renderer MUST render a node of a template component as the expansion of the ro - keep one runtime per node, so the template's local state lives as long as the node and survives updates of its properties; when its properties change, the runtime's arguments MUST be replaced (which keeps the state); - render each host widget node as the renderer renders the child node it stands for; - apply the effects of requirement 6 with the renderer's own mechanisms: dispatch an action from the node's component on the node's surface, invoke the action synchronously in the gesture that fired it, write through the property's binding; -- report the expansion's errors to the host. +- report the expansion's errors to the host; +- when the registry notifies a change (`craft_template_registry`, requirement 10), tell the runtime of every node it renders that the registrations changed, so that template components on screen render the new registrations, with fresh state where their library was registered again, without waiting for an unrelated update. --- @@ -128,7 +129,7 @@ The template receives `label`, the current value of `/user/name` as `value`, the The metadata vocabulary of requirement 2 is a convention between a host's primitives and this feature: `craft_template_registry` reads `args` entries only for being present and not `false`, so they keep their meaning there. -Left out of this feature: v0.9 catalogs (the schemas are v1.0); templates calling components of other catalogs from inside a template (an agent can still pass any catalog's component as a child); `default` values and descriptions in schemas; mapping the surface theme to templates; forwarding expansion errors, including those of `craft_limits`, to the agent (they reach the host's error callback only); and rebuilding a catalog when the registry changes (a host makes a new catalog). +Left out of this feature: v0.9 catalogs (the schemas are v1.0); templates calling components of other catalogs from inside a template (an agent can still pass any catalog's component as a child); `default` values and descriptions in schemas; mapping the surface theme to templates; forwarding expansion errors, including those of `craft_limits`, to the agent (they reach the host's error callback only); and rebuilding a catalog's components and schemas when the registry changes (a host makes a new catalog; components already on screen render the new registrations, requirement 7). --- @@ -154,7 +155,7 @@ The shared cases are in `conformance/craft/craft_a2ui_integration.yaml`. Each ca - **Props to arguments**: values with nulls inside, a null value and no prop; a path-bound value and its setter, also without a value, and an unbound value without one; a path-bound value whose setter name is a property of its own, with and without its own prop; actions, a child and a child list as host values; props of another shape and props that are no property; check results of a checkable component, of other shapes, and of a component that is not checkable. - **Firing to A2UI**: an event's context as JSON, merged with the event arguments; an action run with and without a handler application; setters writing values, structured values, and nothing without a value; a handler list in order. -The engine's unit tests additionally cover what the YAML cannot express: a resolved value that is not JSON, a host handler that stands for nothing, a setter fired with an absent value, the renderer's objects carried by the effects, and resolved values beyond the limits (100,000 deep, and 100 deep as an entry of the arguments, with a control just within). Requirement 7 is covered by widget tests of the Flutter template catalog: an A2UI surface rendering a template from `createSurface`, `updateComponents` and `updateDataModel` messages, data and property updates keeping local state, a two-way write seen by another component, an agent action, a template event, a child of another catalog, check results, a bound value beyond the limits (reported, shown as the placeholder, and recovered from with local state kept), and the schemas of the catalog. +The engine's unit tests additionally cover what the YAML cannot express: a resolved value that is not JSON, a host handler that stands for nothing, a setter fired with an absent value, the renderer's objects carried by the effects, and resolved values beyond the limits (100,000 deep, and 100 deep as an entry of the arguments, with a control just within). Requirement 7 is covered by widget tests of the Flutter template catalog: an A2UI surface rendering a template from `createSurface`, `updateComponents` and `updateDataModel` messages, data and property updates keeping local state, a two-way write seen by another component, an agent action, a template event, a child of another catalog, check results, a bound value beyond the limits (reported, shown as the placeholder, and recovered from with local state kept), the schemas of the catalog, a template library registered again while its component is on screen (re-rendered in the next frame with fresh state, and the first tap after it counted), the media class a template component sees with each media source of the catalog, a template component inside `IntrinsicWidth` and `IntrinsicHeight` with each media source, and a host's error placeholder. --- diff --git a/craft/blueprints/features/craft_media_context.blueprint.md b/craft/blueprints/features/craft_media_context.blueprint.md index f80fb3bd..a6be87d8 100644 --- a/craft/blueprints/features/craft_media_context.blueprint.md +++ b/craft/blueprints/features/craft_media_context.blueprint.md @@ -92,7 +92,7 @@ widget Inbox = switch atLeast(a: media.width, b: "expanded") { On a phone in portrait (`compact`), `Inbox` is one column, with a hint on iOS; on a tablet in landscape (`expanded`) or wider, two panes. When the surface is resized across 840 logical pixels, the host gives the runtime a new media context; the runtime notifies, and the next expansion has the other layout. A template must not assume a media context: without one, `media.width` is absent, `atLeast` gives absent and the switch takes its default. -The width breakpoints are those of Material 3's window size classes, and the height breakpoints those of Android's window size classes; here they apply to the space that the host measures for the surface, which need not be the whole window. A host that renders into a part of the screen (a pane, a card in a list) can measure that part, so that a template adapts to the space it actually gets. +The width breakpoints are those of Material 3's window size classes, and the height breakpoints those of Android's window size classes; here they apply to the space that the host measures for the surface, which need not be the whole window. A host that renders into a part of the screen (a pane, a card in a list) can measure that part, so that a template adapts to the space it actually gets. Measuring takes a layout, so a host that measures must still have something to show before it: a framework that asks a widget for its intrinsic size before laying it out (Flutter's `IntrinsicWidth`, dialogs, tables) needs the template's expansion for some media context first. The Flutter adapter uses the window's size until the first layout and the measured space after it (see the `a2ui_craft_flutter` codebase blueprint). Compared with the prototype: diff --git a/craft/blueprints/features/craft_runtime.blueprint.md b/craft/blueprints/features/craft_runtime.blueprint.md index 9be8e938..4c4b0229 100644 --- a/craft/blueprints/features/craft_runtime.blueprint.md +++ b/craft/blueprints/features/craft_runtime.blueprint.md @@ -117,7 +117,7 @@ The host fires a value of an expansion, with **event arguments**: a map of value ### **10. Local state** - A template declaration with initial state that is expanded at a path `P` MUST have an **instance** identified by `P` and the template's name, even when its root then fails. The first time, its state MUST be a copy of the declaration's initial state; afterwards the instance keeps its state. -- When the library declaring the template is registered again (even with the same source), the instance MUST start again from the initial state. +- When the library declaring the template is registered again (even with the same source), the instance MUST start again from the initial state. The runtime MUST drop the instance as soon as the host says that the registrations changed (requirement 13), not at the next expansion, so that a handler of an earlier expansion that sets its state fails with `unknownState` instead of setting state that the next expansion would throw away. - `state` references MUST read the **nearest stateful instance**: in a template's root, the template's own instance when it has initial state, and otherwise the nearest stateful instance of the scope of its call; in an argument, that of the scope of the call. Without one, they MUST read absent (and a setter fails, requirement 8). - After each expansion of the root, the runtime MUST keep the instances expanded in it and those whose path starts with the path of one of its builder nodes, and MUST drop every other instance, so a template that leaves the expansion starts from its initial state when it comes back. - Updates of the arguments and the data, and registrations other than that of the template's library, MUST keep the state. @@ -156,7 +156,7 @@ Because an instance is identified by its path and template: ### **13. Updates** - A host MUST be able to replace the root's arguments and the data. The next expansion MUST use the new values and the current registrations of the registry. -- A runtime MUST notify the host when an expansion may have changed: after a change of the arguments or the data, after a firing that set state, and when the host says that the registrations changed (`craft_media_context` adds a change of the media context). +- A runtime MUST notify the host when an expansion may have changed: after a change of the arguments or the data, after a firing that set state, and when the host says that the registrations changed (`craft_media_context` adds a change of the media context). A host learns of changes of the registrations from the registry's notifications (`craft_template_registry`, requirement 10). --- @@ -215,7 +215,7 @@ The shared cases are in `conformance/craft/craft_runtime.yaml`. Each case is tag - **Errors**: errors of each `craft_functions` kind at the innermost primitive, with the parent and siblings intact; an unknown widget failing its parent; the first error in argument order; errors in a template's root and in an argument read; recursion through templates, a self-call and a template passed to itself; a self-call and recursion through templates in a builder's output; the template and line of failures in a template's root, in an argument written by the caller, in a builder, of a builder output that gives no widget, of a self-call, of recursion, of a root that is no widget, and of a list nested too deep (which has no position, the primitive call around it giving the line); no template for a root that names no widget. - **Updates**: data and argument updates; a registry change. -The engine's unit tests additionally cover what the YAML cannot express: theme references; loops outside lists, loop and builder argument references without their loop or builder, and a setter without parts (built with the library model); a loop as a loop's output built with the library model; no position for a library parsed without positions or decoded from the binary format, nor for a failure in such a library that calls a template of a library with positions; columns counted in code points; the messages for a self-call, a function argument that is no value, an event argument and a switch input that are no value, and the template and position in the text of a report; host input that is not a value, host handlers and host widgets in data, builder keys; the same library object registered again, and the registry's generation of a library name; notifications; and expansions that keep what they read after a firing. +The engine's unit tests additionally cover what the YAML cannot express: theme references; loops outside lists, loop and builder argument references without their loop or builder, and a setter without parts (built with the library model); a loop as a loop's output built with the library model; no position for a library parsed without positions or decoded from the binary format, nor for a failure in such a library that calls a template of a library with positions; columns counted in code points; the messages for a self-call, a function argument that is no value, an event argument and a switch input that are no value, and the template and position in the text of a report; host input that is not a value, host handlers and host widgets in data, builder keys; the same library object registered again, and the registry's generation of a library name; an instance dropped when the host says that the registrations changed, before the next expansion, so that an earlier handler sets nothing; notifications; and expansions that keep what they read after a firing. --- diff --git a/craft/blueprints/features/craft_template_registry.blueprint.md b/craft/blueprints/features/craft_template_registry.blueprint.md index 8e3ec33a..dbd3833d 100644 --- a/craft/blueprints/features/craft_template_registry.blueprint.md +++ b/craft/blueprints/features/craft_template_registry.blueprint.md @@ -88,6 +88,15 @@ The **components** of a template library are its exported declarations, in decla - The components offered to the agent for a library MUST be its available components, in declaration order: for a primitive library, all its primitives; for an unavailable template library or a name with no registered library, none. Components that are not offered MUST NOT be presented to the agent. +### **10. Change notifications** + +- A host MUST be able to listen to a registry for changes, and to stop listening. +- The registry MUST notify its listeners once after each change of its registrations: each registration of a template library, a primitive library or host functions that is accepted (also when it registers the same library or functions again), each removal of a library or host functions that was registered, and each change of the application version to a different string. +- A rejected registration, a removal of a name with nothing registered and setting the application version it already has MUST NOT notify. +- A listener removed while the registry notifies MUST NOT be called in that notification if it has not been called yet; a listener added while it notifies is first called for the next change. +- A listener that fails MUST NOT undo the change, fail the registration that made it, or keep the other listeners from being called. The registry MUST report the failure to the host (in this engine, to an error callback given to the registry, by default the zone's uncaught error handler). +- When it notifies, every result of this document MUST already reflect the change. This is how a host learns to tell its runtimes that the registrations changed (`craft_runtime`, requirement 13), for example to update the templates that are on screen after a new version of a library arrives. + --- ## **Detailed Description of Changes** @@ -141,8 +150,9 @@ The shared cases are in `conformance/craft/craft_template_registry.yaml`. Each c - **Dependency declarations**: an optional library that is not an import, requirements for a private or unknown declaration, and widget requirements qualified with the library's own name, rejected, each with a different source than the registered one and a query showing the registry unchanged; control steps. - **Availability**: all imports provided; missing imports (once, in import order), then provided; optional imports; a function library as an import; an unavailable imported template library, then available; host functions providing the name of an unavailable template library, then removed; libraries importing each other; library requirements of each kind, met and unmet, in order; requirements seen from the library; component requirements; `hasWidget` and requirements seeing only available components; primitive and unregistered libraries. - **Offered components**: declaration order, private and unavailable components left out, an unavailable library, a primitive library and an unregistered name. +- **Change notifications**: registrations of each kind, a library registered again, a rejected registration, removals of a registered and an unregistered name, a new and the same application version. -The engine's unit tests additionally cover what the YAML cannot express: metadata that is not a value, null in metadata, the copies of a primitive library and of a dependency declaration taken at registration, the per-library function table, and, for `craft_functions`, that the evaluator leaves symbol references unevaluated when no registry reads them. +The engine's unit tests additionally cover what the YAML cannot express: metadata that is not a value, null in metadata, the copies of a primitive library and of a dependency declaration taken at registration, the per-library function table, a listener removed, a listener removed and one added during a notification, a listener that throws (reported to the registry's callback or the zone, the change applied and later listeners called) and a listener that reads the registry when notified, and, for `craft_functions`, that the evaluator leaves symbol references unevaluated when no registry reads them. --- @@ -151,4 +161,5 @@ The engine's unit tests additionally cover what the YAML cannot express: metadat 1. Let the evaluator read symbol references through a reader the caller supplies. 2. Implement the registry: registration with its rejections, the per-library function table with the introspection functions, symbol references and the application version, dropping derived results on every change. 3. Implement dependency declarations, the availability fixed point, the reports and the offered components. -4. Run the conformance cases. +4. Notify listeners after each change. +5. Run the conformance cases. diff --git a/craft/conformance/conformance_schema.json b/craft/conformance/conformance_schema.json index 75086f09..3c542eca 100644 --- a/craft/conformance/conformance_schema.json +++ b/craft/conformance/conformance_schema.json @@ -1234,6 +1234,11 @@ "rejected": { "const": true }, + "notifications": { + "type": "integer", + "minimum": 0, + "description": "How many times the step's registrations notified the registry's listeners." + }, "queries": { "type": "array", "items": { diff --git a/craft/conformance/craft/craft_template_registry.yaml b/craft/conformance/craft/craft_template_registry.yaml index c1b7a278..5b5c69f6 100644 --- a/craft/conformance/craft/craft_template_registry.yaml +++ b/craft/conformance/craft/craft_template_registry.yaml @@ -41,6 +41,9 @@ # app_version: the application version string (initially ""). # rejected: true when the step's single registration must be rejected, # leaving the registry unchanged. +# notifications: how many times the step's registrations, applied in the +# order above, notify the registry's listeners (not checked when not +# given). # queries: checked after the step's registrations, each with an `expect`: # evaluate: L evaluates the `value` argument of the root of the # declaration `declaration` (default `probe`) of @@ -1202,3 +1205,37 @@ expect: [Text, Box] - offered: nope expect: [] + +# change_notifications + +- name: each_accepted_change_notifies_once + action: update_registry + features: [F-CRAFT-REG-10] + description: "Each accepted registration, removal and new app version notifies the listeners once, also when the same source is registered again; a rejected registration, removing nothing and setting the same app version notify nothing." + register: + primitives: + core: {Text: {}} + functions: + fmt: {price: {amount: number}} + libraries: + main: | + import core; + export widget A = Text(); + notifications: 3 + changes: + - libraries: + main: | + import core; + export widget A = Text(); + notifications: 1 + - functions: + core: {f: {}} + rejected: true + notifications: 0 + - remove_libraries: [main, nope] + remove_functions: [fmt, nope] + notifications: 2 + - app_version: "2.0" + notifications: 1 + - app_version: "2.0" + notifications: 0 diff --git a/craft/conformance/features.yaml b/craft/conformance/features.yaml index 1b6df33a..59a30c9b 100644 --- a/craft/conformance/features.yaml +++ b/craft/conformance/features.yaml @@ -365,6 +365,12 @@ blueprintAnchor: blueprints/features/craft_template_registry.blueprint.md#9-offered-components claimedBy: - dart-craft +- id: F-CRAFT-REG-10 + title: "Template Registry: change notifications" + specAnchor: blueprints/features/craft_template_registry.blueprint.md#10-change-notifications + blueprintAnchor: blueprints/features/craft_template_registry.blueprint.md#10-change-notifications + claimedBy: + - dart-craft - id: F-CRAFT-RT-01 title: "Runtime: expansion" specAnchor: blueprints/features/craft_runtime.blueprint.md#1-expansion diff --git a/craft/packages/a2ui_craft/lib/a2ui_craft.dart b/craft/packages/a2ui_craft/lib/a2ui_craft.dart index e2c6a736..eb4c18b2 100644 --- a/craft/packages/a2ui_craft/lib/a2ui_craft.dart +++ b/craft/packages/a2ui_craft/lib/a2ui_craft.dart @@ -15,20 +15,41 @@ /// The framework-independent core of Craft: the template language, its data /// model, its formats and the runtime that expands templates. It has no /// UI-framework dependency, so any framework adapter can build on it. +/// +/// Of the library model it exports a library's structure (imports and +/// declarations) and the types that its other declarations name; the nodes +/// of a declaration's body (`Switch`, `Loop`, `ConstructorCall`, ...) are in +/// `package:a2ui_craft/model.dart`, so that hosts can import this library +/// next to Flutter's without hiding names. library; export 'src/a2ui_catalog.dart'; export 'src/a2ui_props.dart'; export 'src/canonical_json.dart'; export 'src/dependencies.dart'; -export 'src/evaluator.dart'; +export 'src/evaluator.dart' hide checkCallArguments; export 'src/expansion.dart'; export 'src/functions.dart'; export 'src/limits.dart'; export 'src/media_context.dart'; export 'src/name_resolution.dart'; export 'src/rfw/binary.dart'; -export 'src/rfw/model.dart'; +export 'src/rfw/model.dart' + show + BlobNode, + DynamicList, + DynamicMap, + FullyQualifiedWidgetName, + Import, + LibraryName, + Missing, + RemoteWidgetLibrary, + SourceLocation, + SourceRange, + SymbolReference, + WidgetDeclaration, + WidgetLibrary, + missing; export 'src/rfw/text.dart'; export 'src/runtime.dart'; export 'src/standard_functions.dart'; diff --git a/craft/packages/a2ui_craft/lib/model.dart b/craft/packages/a2ui_craft/lib/model.dart new file mode 100644 index 00000000..0bba0b4e --- /dev/null +++ b/craft/packages/a2ui_craft/lib/model.dart @@ -0,0 +1,22 @@ +// Copyright 2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +/// The library model of Craft: the nodes of a parsed template library, which +/// tools that inspect or build libraries use. Its types that the API of +/// `package:a2ui_craft/a2ui_craft.dart` names (`LibraryName`, +/// `RemoteWidgetLibrary`, `WidgetDeclaration`, `Missing`, ...) are exported +/// there too. +library; + +export 'src/rfw/model.dart'; diff --git a/craft/packages/a2ui_craft/lib/src/runtime.dart b/craft/packages/a2ui_craft/lib/src/runtime.dart index be62051a..abab8e24 100644 --- a/craft/packages/a2ui_craft/lib/src/runtime.dart +++ b/craft/packages/a2ui_craft/lib/src/runtime.dart @@ -218,8 +218,17 @@ class CraftRuntime { void removeListener(void Function() listener) => _listeners.remove(listener); /// Tells listeners that the registry changed, or that an expansion may - /// have changed for another reason (see [setMedia]). - void refresh() => _notify(); + /// have changed for another reason (see [setMedia]). First drops the state + /// of every instance whose template's library was registered again or + /// removed, so that its old handlers set nothing (see the `craft_runtime` + /// blueprint, requirement 10). + void refresh() { + _instances.removeWhere( + (String key, StateInstance instance) => + instance.generation != registry.generation(instance.widget.library), + ); + _notify(); + } void _notify() { for (final void Function() listener in List.of( diff --git a/craft/packages/a2ui_craft/lib/src/template_registry.dart b/craft/packages/a2ui_craft/lib/src/template_registry.dart index b32c5e93..8ebbaa0e 100644 --- a/craft/packages/a2ui_craft/lib/src/template_registry.dart +++ b/craft/packages/a2ui_craft/lib/src/template_registry.dart @@ -12,6 +12,8 @@ // See the License for the specific language governing permissions and // limitations under the License. +import 'dart:async'; + import 'dependencies.dart'; import 'evaluator.dart'; import 'functions.dart'; @@ -48,10 +50,18 @@ const Set introspectionFunctionNames = { class TemplateRegistry { /// Creates an empty registry that reports [appVersion] to templates and /// checks libraries and expansions against [limits] (by default - /// [CraftLimits.defaults]). - TemplateRegistry({String appVersion = '', CraftLimits? limits}) - : _appVersion = appVersion, - limits = limits ?? CraftLimits.defaults; + /// [CraftLimits.defaults]). A listener that throws is reported to + /// [onListenerError], by default to the current zone's uncaught error + /// handler. + TemplateRegistry({ + String appVersion = '', + CraftLimits? limits, + this.onListenerError, + }) : _appVersion = appVersion, + limits = limits ?? CraftLimits.defaults; + + /// Receives what a listener throws (see [addListener]). + final void Function(Object error, StackTrace stackTrace)? onListenerError; /// The limits of the libraries registered here, and of evaluations and /// expansions over them (see the `craft_limits` blueprint). @@ -76,10 +86,28 @@ class TemplateRegistry { /// The string that `appVersion()` gives. String get appVersion => _appVersion; set appVersion(String value) { + if (value == _appVersion) return; _appVersion = value; _invalidate(); } + final List _listeners = []; + + /// Calls [listener] after each change of the registrations: a library or + /// host functions registered (also again, unchanged) or removed, and a new + /// [appVersion]. A rejected registration and a removal of nothing change + /// nothing. Runtimes over this registry are told with + /// `CraftRuntime.refresh`; `CraftView` does that while it shows one. + /// + /// A listener removed while listeners are being called is not called any + /// more, one added is first called for the next change. What a listener + /// throws goes to [onListenerError]: the change stays applied, and the + /// other listeners are called. + void addListener(void Function() listener) => _listeners.add(listener); + + /// Stops calling [listener]. + void removeListener(void Function() listener) => _listeners.remove(listener); + /// Registers the template library [library] as [name], replacing any /// library of that name, with its declared [dependencies]. /// @@ -179,6 +207,19 @@ class TemplateRegistry { resolver.invalidate(); _functionTables.clear(); _availability = null; + for (final void Function() listener in List.of( + _listeners, + )) { + if (!_listeners.contains(listener)) continue; + try { + listener(); + } on Object catch (error, stackTrace) { + (onListenerError ?? Zone.current.handleUncaughtError)( + error, + stackTrace, + ); + } + } } // --- Functions and evaluation --------------------------------------------- diff --git a/craft/packages/a2ui_craft/test/a2ui_integration_test.dart b/craft/packages/a2ui_craft/test/a2ui_integration_test.dart index 0a070f06..9c792e6c 100644 --- a/craft/packages/a2ui_craft/test/a2ui_integration_test.dart +++ b/craft/packages/a2ui_craft/test/a2ui_integration_test.dart @@ -16,6 +16,7 @@ // Test Cases section of its blueprint). import 'package:a2ui_craft/a2ui_craft.dart'; +import 'package:a2ui_craft/model.dart'; import 'package:test/test.dart'; void main() { diff --git a/craft/packages/a2ui_craft/test/binary_test.dart b/craft/packages/a2ui_craft/test/binary_test.dart index fdd81085..b424cd55 100644 --- a/craft/packages/a2ui_craft/test/binary_test.dart +++ b/craft/packages/a2ui_craft/test/binary_test.dart @@ -18,6 +18,7 @@ import 'dart:typed_data'; import 'package:a2ui_craft/a2ui_craft.dart'; +import 'package:a2ui_craft/model.dart'; import 'package:test/test.dart'; void main() { diff --git a/craft/packages/a2ui_craft/test/canonical_json_test.dart b/craft/packages/a2ui_craft/test/canonical_json_test.dart index 2a8c21f9..033f68b6 100644 --- a/craft/packages/a2ui_craft/test/canonical_json_test.dart +++ b/craft/packages/a2ui_craft/test/canonical_json_test.dart @@ -16,6 +16,7 @@ // produces; the conformance cases cover the rest. import 'package:a2ui_craft/a2ui_craft.dart'; +import 'package:a2ui_craft/model.dart'; import 'package:test/test.dart'; void main() { diff --git a/craft/packages/a2ui_craft/test/conformance/functions_test.dart b/craft/packages/a2ui_craft/test/conformance/functions_test.dart index 188b1a0a..4cf49be9 100644 --- a/craft/packages/a2ui_craft/test/conformance/functions_test.dart +++ b/craft/packages/a2ui_craft/test/conformance/functions_test.dart @@ -17,6 +17,7 @@ // the case format, the primitive libraries and the test host functions. import 'package:a2ui_craft/a2ui_craft.dart'; +import 'package:a2ui_craft/model.dart'; import 'package:test/test.dart'; import 'conformance_harness.dart'; diff --git a/craft/packages/a2ui_craft/test/conformance/limits_test.dart b/craft/packages/a2ui_craft/test/conformance/limits_test.dart index 4178d72b..4325443d 100644 --- a/craft/packages/a2ui_craft/test/conformance/limits_test.dart +++ b/craft/packages/a2ui_craft/test/conformance/limits_test.dart @@ -19,6 +19,7 @@ import 'dart:typed_data'; import 'package:a2ui_craft/a2ui_craft.dart'; +import 'package:a2ui_craft/model.dart'; import 'package:test/test.dart'; import 'conformance_harness.dart'; diff --git a/craft/packages/a2ui_craft/test/conformance/media_context_test.dart b/craft/packages/a2ui_craft/test/conformance/media_context_test.dart index dbcef464..50e987b0 100644 --- a/craft/packages/a2ui_craft/test/conformance/media_context_test.dart +++ b/craft/packages/a2ui_craft/test/conformance/media_context_test.dart @@ -17,6 +17,7 @@ // the case format. import 'package:a2ui_craft/a2ui_craft.dart'; +import 'package:a2ui_craft/model.dart'; import 'package:test/test.dart'; import 'conformance_harness.dart'; diff --git a/craft/packages/a2ui_craft/test/conformance/template_registry_test.dart b/craft/packages/a2ui_craft/test/conformance/template_registry_test.dart index 2f78e35a..870b5d21 100644 --- a/craft/packages/a2ui_craft/test/conformance/template_registry_test.dart +++ b/craft/packages/a2ui_craft/test/conformance/template_registry_test.dart @@ -17,6 +17,7 @@ // documents the case format. import 'package:a2ui_craft/a2ui_craft.dart'; +import 'package:a2ui_craft/model.dart'; import 'package:test/test.dart'; import 'conformance_harness.dart'; @@ -56,8 +57,12 @@ class _Engine { 'remove_functions', 'app_version', 'rejected', + 'notifications', 'queries', }, 'step'); + int notifications = 0; + void listener() => notifications += 1; + registry.addListener(listener); final List registrations = [ for (final MapEntry p in _entries(step['primitives'])) () => registry.setPrimitiveLibrary( @@ -107,6 +112,10 @@ class _Engine { register(); } } + registry.removeListener(listener); + if (step.containsKey('notifications')) { + expect(notifications, step['notifications'], reason: 'notifications'); + } for (final Object? q in step['queries'] as List? ?? []) { query(q! as Map); } diff --git a/craft/packages/a2ui_craft/test/error_messages_test.dart b/craft/packages/a2ui_craft/test/error_messages_test.dart index 8507ea28..c6c95f14 100644 --- a/craft/packages/a2ui_craft/test/error_messages_test.dart +++ b/craft/packages/a2ui_craft/test/error_messages_test.dart @@ -17,6 +17,7 @@ // requirement 12, and craft_text_format, requirement 6). import 'package:a2ui_craft/a2ui_craft.dart'; +import 'package:a2ui_craft/model.dart'; import 'package:test/test.dart'; const LibraryName _main = LibraryName(['main']); diff --git a/craft/packages/a2ui_craft/test/functions_test.dart b/craft/packages/a2ui_craft/test/functions_test.dart index 5473b935..ed46353b 100644 --- a/craft/packages/a2ui_craft/test/functions_test.dart +++ b/craft/packages/a2ui_craft/test/functions_test.dart @@ -19,6 +19,7 @@ // without a symbol reader. import 'package:a2ui_craft/a2ui_craft.dart'; +import 'package:a2ui_craft/model.dart'; import 'package:test/test.dart'; const LibraryName _test = LibraryName(['test']); diff --git a/craft/packages/a2ui_craft/test/language_extensions_test.dart b/craft/packages/a2ui_craft/test/language_extensions_test.dart index e91e27a4..8e3680b3 100644 --- a/craft/packages/a2ui_craft/test/language_extensions_test.dart +++ b/craft/packages/a2ui_craft/test/language_extensions_test.dart @@ -16,6 +16,7 @@ // nodes the parser builds for them. import 'package:a2ui_craft/a2ui_craft.dart'; +import 'package:a2ui_craft/model.dart'; import 'package:test/test.dart'; Object? _rootArg(String source, String arg) => diff --git a/craft/packages/a2ui_craft/test/limits_test.dart b/craft/packages/a2ui_craft/test/limits_test.dart index 2f7f0a5f..4d681286 100644 --- a/craft/packages/a2ui_craft/test/limits_test.dart +++ b/craft/packages/a2ui_craft/test/limits_test.dart @@ -19,6 +19,7 @@ import 'dart:typed_data'; import 'package:a2ui_craft/a2ui_craft.dart'; +import 'package:a2ui_craft/model.dart'; import 'package:test/test.dart'; const LibraryName _main = LibraryName(['main']); diff --git a/craft/packages/a2ui_craft/test/media_context_test.dart b/craft/packages/a2ui_craft/test/media_context_test.dart index 111bfd8e..766f55bb 100644 --- a/craft/packages/a2ui_craft/test/media_context_test.dart +++ b/craft/packages/a2ui_craft/test/media_context_test.dart @@ -18,6 +18,7 @@ // context as a host API. import 'package:a2ui_craft/a2ui_craft.dart'; +import 'package:a2ui_craft/model.dart'; import 'package:test/test.dart'; const LibraryName _main = LibraryName(['main']); diff --git a/craft/packages/a2ui_craft/test/public_api_test.dart b/craft/packages/a2ui_craft/test/public_api_test.dart new file mode 100644 index 00000000..18d584e4 --- /dev/null +++ b/craft/packages/a2ui_craft/test/public_api_test.dart @@ -0,0 +1,56 @@ +// Copyright 2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// The main library exports every library model type that its API names, so a +// host can name them without package:a2ui_craft/model.dart. This file only +// compiles while that holds. + +import 'package:a2ui_craft/a2ui_craft.dart'; +import 'package:test/test.dart'; + +void main() { + test('the types the API names are exported', () { + final RemoteWidgetLibrary library = parseLibraryFile( + 'import core; widget root { n: 0 } = Text(text: Logo.version);', + ); + final List imports = library.imports; + final List widgets = library.widgets; + final BlobNode node = widgets.single; + final TemplateRegistry registry = TemplateRegistry() + ..setTemplateLibrary(const LibraryName(['main']), library); + final SymbolReader reader = registry.readSymbol; + const SymbolReference symbol = SymbolReference('Logo', ['version']); + final Object value = reader(const LibraryName(['main']), symbol); + final CraftRuntime runtime = CraftRuntime( + registry, + library: const LibraryName(['main']), + widget: 'root', + ); + final WidgetDeclaration declaration = runtime + .expand() + .states + .single + .instance + .declaration; + final WidgetDeclaration? resolved = + (registry.resolver.resolve(const LibraryName(['main']), 'root') + as ResolvedName) + .declaration; + expect(imports.single.name, coreLibrary); + expect(node.source, isNull); + expect(value, missing); + expect(identical(declaration, widgets.single), isTrue); + expect(identical(resolved, widgets.single), isTrue); + }); +} diff --git a/craft/packages/a2ui_craft/test/rfw/binary_test.dart b/craft/packages/a2ui_craft/test/rfw/binary_test.dart index 954b37e3..0f2ca43f 100644 --- a/craft/packages/a2ui_craft/test/rfw/binary_test.dart +++ b/craft/packages/a2ui_craft/test/rfw/binary_test.dart @@ -21,6 +21,7 @@ import 'dart:typed_data'; import 'package:a2ui_craft/a2ui_craft.dart'; +import 'package:a2ui_craft/model.dart'; import 'package:test/test.dart'; // This is a number that requires more than 32 bits but less than 53 bits, so diff --git a/craft/packages/a2ui_craft/test/rfw/model_test.dart b/craft/packages/a2ui_craft/test/rfw/model_test.dart index 1c5a0ec9..c2579c8a 100644 --- a/craft/packages/a2ui_craft/test/rfw/model_test.dart +++ b/craft/packages/a2ui_craft/test/rfw/model_test.dart @@ -3,7 +3,7 @@ // found in the LICENSE file. import 'package:test/test.dart'; -import 'package:a2ui_craft/a2ui_craft.dart'; +import 'package:a2ui_craft/model.dart'; void main() { test('$LibraryName', () async { diff --git a/craft/packages/a2ui_craft/test/runtime_test.dart b/craft/packages/a2ui_craft/test/runtime_test.dart index 62d39c2b..57c9d043 100644 --- a/craft/packages/a2ui_craft/test/runtime_test.dart +++ b/craft/packages/a2ui_craft/test/runtime_test.dart @@ -17,6 +17,7 @@ // host input, and the runtime's notifications and snapshots. import 'package:a2ui_craft/a2ui_craft.dart'; +import 'package:a2ui_craft/model.dart'; import 'package:test/test.dart'; const LibraryName _main = LibraryName(['main']); @@ -276,6 +277,35 @@ void main() { expect(calls, 4); }); + test('refresh drops the state of a library registered again', () { + final RemoteWidgetLibrary library = parseLibraryFile(counter); + final TemplateRegistry registry = _registry(library); + final CraftRuntime runtime = CraftRuntime( + registry, + library: _main, + widget: 'root', + ); + final WidgetNode box = runtime.expand().root as WidgetNode; + registry.setPrimitiveLibrary( + const LibraryName(['other']), + _Core(), + ); + runtime.refresh(); + expect( + runtime.fire(box.arguments['inc']!).stateChanged, + isTrue, + reason: 'another registration keeps the state', + ); + registry.setTemplateLibrary(_main, library); + runtime.refresh(); + final FireResult result = runtime.fire(box.arguments['inc']!); + expect(result.stateChanged, isFalse); + expect(result.errors.single.kind, FireErrorKind.unknownState); + expect(runtime.expand().states.single.value, { + 'list': [0], + }); + }); + test('an expansion keeps what it read when state changes', () { final CraftRuntime runtime = _parsed(counter); final Expansion before = runtime.expand(); diff --git a/craft/packages/a2ui_craft/test/template_registry_test.dart b/craft/packages/a2ui_craft/test/template_registry_test.dart index 72297b8c..2a0a155a 100644 --- a/craft/packages/a2ui_craft/test/template_registry_test.dart +++ b/craft/packages/a2ui_craft/test/template_registry_test.dart @@ -18,7 +18,10 @@ // declaration taken at registration, and the function table the registry builds // for each library. +import 'dart:async'; + import 'package:a2ui_craft/a2ui_craft.dart'; +import 'package:a2ui_craft/model.dart'; import 'package:test/test.dart'; const LibraryName _core = LibraryName(['core']); @@ -47,6 +50,65 @@ Object _probe(TemplateRegistry registry, String expression) { } void main() { + test('a listener removed during a notification is not called', () { + final TemplateRegistry registry = TemplateRegistry(); + final List calls = []; + void second() => calls.add('second'); + void added() => calls.add('added'); + registry + ..addListener(() { + calls.add('first'); + registry + ..removeListener(second) + ..addListener(added); + }) + ..addListener(second) + ..appVersion = '1'; + expect(calls, ['first']); + registry.appVersion = '2'; + expect(calls, ['first', 'first', 'added']); + }); + + test('a throwing listener neither fails the change nor stops others', () { + final List reported = []; + final TemplateRegistry registry = TemplateRegistry( + onListenerError: (Object error, StackTrace stackTrace) => + reported.add(error), + ); + int later = 0; + registry + ..addListener(() => throw StateError('listener')) + ..addListener(() => later += 1); + expect(() => registry.appVersion = '1', returnsNormally); + expect(registry.appVersion, '1'); + expect(later, 1); + expect(reported.single, isA()); + }); + + test('without a callback a listener failure goes to the zone', () { + final List uncaught = []; + runZonedGuarded(() { + final TemplateRegistry registry = TemplateRegistry() + ..addListener(() => throw StateError('listener')); + registry.appVersion = '1'; + expect(registry.appVersion, '1'); + }, (Object error, StackTrace stackTrace) => uncaught.add(error)); + expect(uncaught.single, isA()); + }); + + test('listeners hear each change, already applied, until removed', () { + final TemplateRegistry registry = TemplateRegistry(); + final List seen = []; + void listener() => seen.add(registry.availability(_main) != null); + registry + ..addListener(listener) + ..setTemplateLibrary(_main, parseLibraryFile('widget A = B();')) + ..removeLibrary(_main) + ..removeListener(listener) + ..setTemplateLibrary(_main, parseLibraryFile('widget A = B();')); + expect(seen, [true, false]); + }); + test('metadata that is not a value is rejected at registration', () { final TemplateRegistry registry = TemplateRegistry() ..setPrimitiveLibrary( diff --git a/craft/packages/a2ui_craft/test/text_format_test.dart b/craft/packages/a2ui_craft/test/text_format_test.dart index 23506976..0946a7a4 100644 --- a/craft/packages/a2ui_craft/test/text_format_test.dart +++ b/craft/packages/a2ui_craft/test/text_format_test.dart @@ -16,6 +16,7 @@ // conformance cases can: error messages and parsed nodes. import 'package:a2ui_craft/a2ui_craft.dart'; +import 'package:a2ui_craft/model.dart'; import 'package:test/test.dart'; Matcher _rejected(String message) => throwsA( diff --git a/craft/packages/a2ui_craft_flutter/lib/src/craft_view.dart b/craft/packages/a2ui_craft_flutter/lib/src/craft_view.dart index 5ac01d56..dab2ae66 100644 --- a/craft/packages/a2ui_craft_flutter/lib/src/craft_view.dart +++ b/craft/packages/a2ui_craft_flutter/lib/src/craft_view.dart @@ -18,6 +18,7 @@ import 'package:flutter/scheduler.dart'; import 'package:flutter/widgets.dart'; import 'primitive_widgets.dart'; +import 'space_builder.dart'; /// A node of an expansion that the adapter cannot render: a primitive with /// no [PrimitiveWidget] in the libraries given to [CraftView]. @@ -38,9 +39,10 @@ class MissingPrimitiveWidget { enum MediaSource { /// The space the view is given: the maximum width and height of its /// layout constraints, an unbounded one replaced by that of the size of - /// the nearest [MediaQuery]. Like every [LayoutBuilder], the view then - /// cannot answer intrinsic size queries; use [window] or [host] where a - /// parent asks them. + /// the nearest [MediaQuery]. Before its first layout the view takes the + /// [MediaQuery] size, and it answers intrinsic size queries (as in + /// [IntrinsicWidth]) with the expansion it last rendered, so at first with + /// the one for the [MediaQuery] size. layout, /// The size of the nearest [MediaQuery]: the window in an app. @@ -51,7 +53,10 @@ enum MediaSource { } /// Renders the expansion of [runtime] with the widgets of [libraries], and -/// expands it again whenever the runtime notifies a change. +/// expands it again whenever the runtime notifies a change. When the +/// runtime's registry notifies a change, the view calls +/// [CraftRuntime.refresh], so that templates on screen follow new +/// registrations. /// /// Unless [media] is [MediaSource.host], the view sets the runtime's media /// context before it renders (see [MediaContext.fromSize]): a size from @@ -113,7 +118,14 @@ class CraftView extends StatefulWidget { class _CraftViewState extends State { /// The expansion rendered; null when the runtime changed since. Expansion? _expansion; - final List _pendingErrors = []; + + /// The errors to report after the frame, each with the expansion it was + /// found in (null for a firing's errors). + final List<(Expansion?, Object)> _pendingErrors = <(Expansion?, Object)>[]; + + /// The last expansion of the root; errors of earlier ones that are still + /// pending were superseded in the same frame and are not reported. + Expansion? _latest; bool _expansionScheduled = false; /// Whether the view is notifying of its own media change, so that it @@ -131,29 +143,42 @@ class _CraftViewState extends State { @override void initState() { super.initState(); - widget.runtime.addListener(_changed); + _listen(widget.runtime); } @override void didUpdateWidget(CraftView oldWidget) { super.didUpdateWidget(oldWidget); if (!identical(oldWidget.runtime, widget.runtime)) { - oldWidget.runtime.removeListener(_changed); - widget.runtime.addListener(_changed); + _stopListening(oldWidget.runtime); + _listen(widget.runtime); _expansion = null; } } @override void dispose() { - widget.runtime.removeListener(_changed); + _stopListening(widget.runtime); super.dispose(); } + void _listen(CraftRuntime runtime) { + runtime.addListener(_changed); + runtime.registry.addListener(_registryChanged); + } + + void _stopListening(CraftRuntime runtime) { + runtime.removeListener(_changed); + runtime.registry.removeListener(_registryChanged); + } + + /// Tells the runtime, which drops stale state at once and notifies. + void _registryChanged() => widget.runtime.refresh(); + Expansion _expand() { - final Expansion expansion = widget.runtime.expand(); + final Expansion expansion = _latest = widget.runtime.expand(); _reported.clear(); - _report(expansion.errors); + _report(expansion.errors, of: expansion); return expansion; } @@ -213,16 +238,21 @@ class _CraftViewState extends State { /// Reports [error] unless it was already reported for this expansion. void _reportOnce(String key, Object error) { - if (_reported.add(key)) _report([error]); + if (_reported.add(key)) _report([error], of: _latest); } - void _report(Iterable errors) { + void _report(Iterable errors, {required Expansion? of}) { if (errors.isEmpty || widget.onError == null) return; final bool schedule = _pendingErrors.isEmpty; - _pendingErrors.addAll(errors); + _pendingErrors.addAll(<(Expansion?, Object)>[ + for (final Object error in errors) (of, error), + ]); if (!schedule) return; SchedulerBinding.instance.addPostFrameCallback((Duration _) { - final List errors = List.of(_pendingErrors); + final List errors = [ + for (final (Expansion? of, Object error) in _pendingErrors) + if (of == null || identical(of, _latest)) error, + ]; _pendingErrors.clear(); final ValueChanged? onError = widget.onError; if (mounted && onError != null) errors.forEach(onError); @@ -235,7 +265,7 @@ class _CraftViewState extends State { if (widget.onEvent case final ValueChanged onEvent) { result.events.forEach(onEvent); } - _report(result.errors); + _report(result.errors, of: null); } Widget _buildOutput(BuilderNode builder, Object key, Object? argument) { @@ -276,20 +306,15 @@ class _CraftViewState extends State { _setMedia(context, MediaQuery.sizeOf(context)); return _renderRoot(); case MediaSource.layout: - return LayoutBuilder( - builder: (BuildContext context, BoxConstraints constraints) { - final Size window = MediaQuery.sizeOf(context); - _setMedia( - context, - Size( - constraints.hasBoundedWidth - ? constraints.maxWidth - : window.width, - constraints.hasBoundedHeight - ? constraints.maxHeight - : window.height, - ), - ); + final Size window = MediaQuery.sizeOf(context); + return SpaceBuilder( + window: window, + builder: (BuildContext context, Size? space) { + // Before the first layout, keep a media context set earlier (by + // another view of the runtime), so that no state is dropped. + if (space != null || widget.runtime.media == null) { + _setMedia(context, space ?? window); + } return _renderRoot(); }, ); diff --git a/craft/packages/a2ui_craft_flutter/lib/src/space_builder.dart b/craft/packages/a2ui_craft_flutter/lib/src/space_builder.dart new file mode 100644 index 00000000..9c2e8f94 --- /dev/null +++ b/craft/packages/a2ui_craft_flutter/lib/src/space_builder.dart @@ -0,0 +1,232 @@ +// Copyright 2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import 'package:flutter/rendering.dart'; +import 'package:flutter/scheduler.dart'; +import 'package:flutter/widgets.dart'; + +/// Builds its child for the space it is given, like [LayoutBuilder], but +/// also answers intrinsic size queries. +/// +/// The space is the maximum size of the layout constraints, an unbounded +/// axis taking that of [window]. A [LayoutBuilder] builds only in layout, so +/// it has no child to ask when a parent such as [IntrinsicWidth] queries its +/// size first. This widget also builds in the build phase, for the space of +/// its last layout (null before the first one), and builds again during +/// layout only when the space differs; intrinsic queries go to the child as +/// last built. +class SpaceBuilder extends RenderObjectWidget { + /// Creates a builder of [builder] under a [window]. + const SpaceBuilder({super.key, required this.window, required this.builder}); + + /// The size of an unbounded axis. + final Size window; + + /// Builds the child for a space, null before the first layout. + final Widget Function(BuildContext context, Size? space) builder; + + @override + RenderObjectElement createElement() => _SpaceBuilderElement(this); + + @override + RenderObject createRenderObject(BuildContext context) => + _RenderSpaceBuilder(); +} + +class _SpaceBuilderElement extends RenderObjectElement { + _SpaceBuilderElement(SpaceBuilder super.widget); + + @override + _RenderSpaceBuilder get renderObject => + super.renderObject as _RenderSpaceBuilder; + + SpaceBuilder get _widget => widget as SpaceBuilder; + + Element? _child; + + /// The space the child was built for. + Size? _builtFor; + bool _built = false; + + /// The space of the last layout. + Size? _laidOutIn; + + // As in LayoutBuilder, descendants rebuild in this element's scope, during + // its render object's layout. + @override + BuildScope get buildScope => _buildScope; + late final BuildScope _buildScope = BuildScope( + scheduleRebuild: _scheduleRebuild, + ); + + bool _deferredCallbackScheduled = false; + + void _scheduleRebuild() { + if (_deferredCallbackScheduled) return; + switch (SchedulerBinding.instance.schedulerPhase) { + case SchedulerPhase.idle || SchedulerPhase.postFrameCallbacks: + _deferredCallbackScheduled = true; + SchedulerBinding.instance.scheduleFrameCallback((Duration _) { + _deferredCallbackScheduled = false; + if (mounted) renderObject.scheduleLayoutCallback(); + }); + case SchedulerPhase.transientCallbacks || + SchedulerPhase.midFrameMicrotasks || + SchedulerPhase.persistentCallbacks: + renderObject.scheduleLayoutCallback(); + } + } + + @override + void visitChildren(ElementVisitor visitor) { + if (_child case final Element child) visitor(child); + } + + @override + void forgetChild(Element child) { + assert(child == _child); + _child = null; + super.forgetChild(child); + } + + @override + void mount(Element? parent, Object? newSlot) { + super.mount(parent, newSlot); + renderObject.element = this; + _build(null); + } + + @override + void update(SpaceBuilder newWidget) { + super.update(newWidget); + _build(_laidOutIn); + renderObject.scheduleLayoutCallback(); + } + + @override + void performRebuild() { + super.performRebuild(); + _build(_laidOutIn); + renderObject.scheduleLayoutCallback(); + } + + @override + void unmount() { + renderObject.element = null; + super.unmount(); + } + + /// Builds the child for [space], in the build phase or a layout callback. + void _build(Size? space) { + _builtFor = space; + _built = true; + _child = updateChild(_child, _widget.builder(this, space), null); + } + + /// Builds the child again when the space of this layout differs from the + /// one it was built for, and rebuilds dirty descendants. + void _layout(BoxConstraints constraints) { + final Size window = _widget.window; + final Size space = Size( + constraints.hasBoundedWidth ? constraints.maxWidth : window.width, + constraints.hasBoundedHeight ? constraints.maxHeight : window.height, + ); + _laidOutIn = space; + owner!.buildScope( + this, + _built && space == _builtFor ? null : () => _build(space), + ); + } + + @override + void insertRenderObjectChild(RenderBox child, Object? slot) { + renderObject.child = child; + } + + @override + void moveRenderObjectChild( + RenderObject child, + Object? oldSlot, + Object? newSlot, + ) { + assert(false); + } + + @override + void removeRenderObjectChild(RenderObject child, Object? slot) { + assert(renderObject.child == child); + renderObject.child = null; + } +} + +class _RenderSpaceBuilder extends RenderBox + with + RenderObjectWithChildMixin, + RenderObjectWithLayoutCallbackMixin { + _SpaceBuilderElement? element; + + @override + void layoutCallback() => element?._layout(constraints); + + @override + double computeMinIntrinsicWidth(double height) => + child?.getMinIntrinsicWidth(height) ?? 0; + + @override + double computeMaxIntrinsicWidth(double height) => + child?.getMaxIntrinsicWidth(height) ?? 0; + + @override + double computeMinIntrinsicHeight(double width) => + child?.getMinIntrinsicHeight(width) ?? 0; + + @override + double computeMaxIntrinsicHeight(double width) => + child?.getMaxIntrinsicHeight(width) ?? 0; + + @override + Size computeDryLayout(BoxConstraints constraints) => + constraints.constrain(child?.getDryLayout(constraints) ?? Size.zero); + + @override + double? computeDryBaseline( + BoxConstraints constraints, + TextBaseline baseline, + ) => child?.getDryBaseline(constraints, baseline); + + @override + void performLayout() { + runLayoutCallback(); + if (child case final RenderBox child) { + child.layout(constraints, parentUsesSize: true); + size = constraints.constrain(child.size); + } else { + size = constraints.smallest; + } + } + + @override + double? computeDistanceToActualBaseline(TextBaseline baseline) => + child?.getDistanceToActualBaseline(baseline) ?? + super.computeDistanceToActualBaseline(baseline); + + @override + bool hitTestChildren(BoxHitTestResult result, {required Offset position}) => + child?.hitTest(result, position: position) ?? false; + + @override + void paint(PaintingContext context, Offset offset) { + if (child case final RenderBox child) context.paintChild(child, offset); + } +} diff --git a/craft/packages/a2ui_craft_flutter/pubspec.yaml b/craft/packages/a2ui_craft_flutter/pubspec.yaml index 5b91faa8..52d21ff2 100644 --- a/craft/packages/a2ui_craft_flutter/pubspec.yaml +++ b/craft/packages/a2ui_craft_flutter/pubspec.yaml @@ -32,6 +32,8 @@ dependencies: sdk: flutter dev_dependencies: + cupertino_ui: ^1.1.7 flutter_test: sdk: flutter lints: ^6.0.0 + material_ui: ^1.11.1 diff --git a/craft/packages/a2ui_craft_flutter/test/craft_view_test.dart b/craft/packages/a2ui_craft_flutter/test/craft_view_test.dart index fc4370a6..c043b418 100644 --- a/craft/packages/a2ui_craft_flutter/test/craft_view_test.dart +++ b/craft/packages/a2ui_craft_flutter/test/craft_view_test.dart @@ -423,6 +423,50 @@ void main() { expect(find.text('b2#${before + 1}'), findsOneWidget); }); + testWidgets('a registration renders again, until the view is gone', ( + WidgetTester tester, + ) async { + final _Harness h = _Harness('import core; widget root = Text(text: "v1");'); + await tester.pumpWidget(h.view()); + expect(find.text('v1'), findsOneWidget); + h.registry.setTemplateLibrary( + _main, + parseLibraryFile('import core; widget root = Text(text: "v2");'), + ); + await tester.pump(); + expect(find.text('v2'), findsOneWidget); + + await tester.pumpWidget(const SizedBox()); + int notified = 0; + h.runtime.addListener(() => notified += 1); + h.registry.setTemplateLibrary( + _main, + parseLibraryFile('import core; widget root = Text(text: "v3");'), + ); + expect(notified, 0, reason: 'the view no longer refreshes the runtime'); + }); + + testWidgets('errors of an expansion replaced in the same frame are dropped', ( + WidgetTester tester, + ) async { + final _Harness h = _Harness(''' + import core; + widget root = switch media.width { "compact": Text(text: "phone") }; + '''); + await tester.pumpWidget( + MediaQuery( + data: const MediaQueryData(size: Size(1300, 1000)), + child: Align( + alignment: Alignment.topLeft, + child: SizedBox(width: 400, height: 800, child: h.view()), + ), + ), + ); + await tester.pump(); + expect(find.text('phone'), findsOneWidget); + expect(h.errors, isEmpty, reason: 'the expansion for the window failed'); + }); + testWidgets('errors are not reported once the view is gone', ( WidgetTester tester, ) async { diff --git a/craft/packages/a2ui_craft_flutter/test/imports_test.dart b/craft/packages/a2ui_craft_flutter/test/imports_test.dart new file mode 100644 index 00000000..84e156be --- /dev/null +++ b/craft/packages/a2ui_craft_flutter/test/imports_test.dart @@ -0,0 +1,44 @@ +// Copyright 2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// A host imports Craft next to the Material and Cupertino libraries without +// hiding names. Dart reports a clash only for a name a file uses, so this file +// uses `Switch`, the name the library model shares with Material. + +import 'package:a2ui_craft/a2ui_craft.dart'; +import 'package:a2ui_craft_flutter/a2ui_craft_flutter.dart'; +import 'package:cupertino_ui/cupertino_ui.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:material_ui/material_ui.dart'; + +void main() { + testWidgets('Craft and Flutter libraries import together', ( + WidgetTester tester, + ) async { + await tester.pumpWidget( + MaterialApp( + home: Material( + child: Column( + children: [ + Switch(value: true, onChanged: (_) {}), + CupertinoSwitch(value: true, onChanged: (_) {}), + ], + ), + ), + ), + ); + expect(coreLibrary, const LibraryName(['core'])); + expect(MediaSource.values, isNotEmpty); + }); +} diff --git a/craft/packages/a2ui_craft_flutter/test/media_test.dart b/craft/packages/a2ui_craft_flutter/test/media_test.dart index f9294828..51f7d782 100644 --- a/craft/packages/a2ui_craft_flutter/test/media_test.dart +++ b/craft/packages/a2ui_craft_flutter/test/media_test.dart @@ -105,11 +105,27 @@ void main() { final _Harness h = _Harness(); await tester.pumpWidget(_sized(h.view(), width: 599, height: 480)); expect(find.text('compact medium landscape android false'), findsOneWidget); - expect(h.expansions, 1, reason: 'no expansion without the media context'); + expect( + h.expansions, + 2, + reason: 'before its first layout the view expands for the window', + ); expect( h.runtime.media, MediaContext.fromSize(599, 480, platform: HostPlatform.android), ); + + final _Harness same = _Harness(); + await tester.pumpWidget( + _sized( + same.view(), + width: 599, + height: 480, + window: const Size(560, 500), + ), + ); + expect(find.text('compact medium landscape android false'), findsOneWidget); + expect(same.expansions, 1, reason: 'the window has the same classes'); }); testWidgets('layout: a resize across a class renders in the same frame', ( @@ -125,17 +141,18 @@ void main() { findsOneWidget, ); expect(notified, 1); + h.expansions = 0; await tester.pumpWidget(_sized(h.view(), width: 590, height: 900)); - expect(h.expansions, 1, reason: 'the same classes'); + expect(h.expansions, 0, reason: 'the same classes'); expect(notified, 1); await tester.pumpWidget(_sized(h.view(), width: 1200, height: 900)); expect(find.text('large expanded landscape android false'), findsOneWidget); - expect(h.expansions, 2); + expect(h.expansions, 1); expect(notified, 2); await tester.pump(); - expect(h.expansions, 2, reason: 'nothing left for the next frame'); + expect(h.expansions, 1, reason: 'nothing left for the next frame'); }); testWidgets('host listeners hear of a media change after the frame', ( @@ -247,22 +264,83 @@ void main() { ); }); - testWidgets('window and host answer intrinsic size queries; layout not', ( + testWidgets('every media source answers intrinsic size queries', ( WidgetTester tester, ) async { _largeSurface(tester); - final _Harness h = _Harness(); - for (final MediaSource media in [ - MediaSource.window, - MediaSource.host, - ]) { - await tester.pumpWidget( - _sized(IntrinsicWidth(child: h.view(media: media))), - ); - expect(tester.takeException(), isNull, reason: media.name); + for (final MediaSource media in MediaSource.values) { + for (final bool width in [true, false]) { + final _Harness h = _Harness(); + if (media == MediaSource.host) { + h.runtime.media = MediaContext.fromSize( + 1300, + 1000, + platform: HostPlatform.android, + ); + } + final Widget view = h.view(media: media); + await tester.pumpWidget( + _sized( + width ? IntrinsicWidth(child: view) : IntrinsicHeight(child: view), + ), + ); + final String reason = '${media.name} ${width ? 'width' : 'height'}'; + expect(tester.takeException(), isNull, reason: reason); + final Size text = tester.getSize(find.byType(Text)); + final Size box = tester.getSize( + find.byType(width ? IntrinsicWidth : IntrinsicHeight), + ); + expect(text.width, greaterThan(100), reason: reason); + if (width) { + expect(box.width, text.width, reason: '$reason: sized to the text'); + } else { + expect(box.height, text.height, reason: '$reason: not 0 px'); + } + + final RenderBox render = tester.renderObject(find.byType(CraftView)); + final double line = text.height; + expect( + render.getMinIntrinsicWidth(double.infinity), + greaterThan(0), + reason: '$reason: min intrinsic width', + ); + expect( + render.getMaxIntrinsicWidth(double.infinity), + greaterThan(100), + reason: '$reason: max intrinsic width', + ); + expect( + render.getMinIntrinsicHeight(2000), + inInclusiveRange(1, line), + reason: '$reason: min intrinsic height', + ); + expect( + render.getMaxIntrinsicHeight(2000), + inInclusiveRange(1, line), + reason: '$reason: max intrinsic height', + ); + final Size dry = render.getDryLayout(BoxConstraints.loose(box)); + expect(dry.height, greaterThan(0), reason: '$reason: dry layout'); + expect(dry.width, greaterThan(0), reason: '$reason: dry layout'); + await tester.pumpWidget(const SizedBox()); + } } - await tester.pumpWidget(_sized(IntrinsicWidth(child: h.view()))); - expect(tester.takeException(), isNotNull); + }); + + testWidgets('layout: a new view keeps the media context of the runtime', ( + WidgetTester tester, + ) async { + _largeSurface(tester); + final _Harness h = _Harness(); + await tester.pumpWidget(_sized(h.view(), width: 500, height: 900)); + await tester.pumpWidget(const SizedBox()); + h.expansions = 0; + await tester.pumpWidget(_sized(h.view(), width: 500, height: 900)); + expect( + find.text('compact expanded portrait android false'), + findsOneWidget, + ); + expect(h.expansions, 1, reason: 'no expansion for the window first'); }); testWidgets('host: the view leaves the media context alone', ( diff --git a/craft/packages/a2ui_craft_renderer_flutter/lib/src/template_catalog.dart b/craft/packages/a2ui_craft_renderer_flutter/lib/src/template_catalog.dart index 10e974bc..5b70349c 100644 --- a/craft/packages/a2ui_craft_renderer_flutter/lib/src/template_catalog.dart +++ b/craft/packages/a2ui_craft_renderer_flutter/lib/src/template_catalog.dart @@ -32,9 +32,15 @@ typedef TemplateErrorCallback = void Function(String componentId, Object error); /// templates. /// /// Each component expands its template with the Flutter widgets of -/// [primitives]. [functions] are what dynamic values and `@checks` on these -/// components may call; the catalog is made from the registrations as they -/// are now. +/// [primitives], in a [CraftView] that takes its media context from [media] +/// and builds the placeholder of a failed widget with [errorBuilder] (by +/// default a small error box). [functions] are what dynamic values and +/// `@checks` on these components may call. +/// +/// The catalog's components and schemas are made from the registrations as +/// they are now. Components on screen follow later registrations: when +/// [registry] notifies a change, they render again, and a template whose +/// library was registered again starts from its initial state. CatalogImplementation templateCatalog({ required String id, required TemplateRegistry registry, @@ -42,6 +48,8 @@ CatalogImplementation templateCatalog({ required Map primitives, List functions = const [], TemplateErrorCallback? onError, + MediaSource media = MediaSource.layout, + Widget Function(BuildContext context, ErrorNode node)? errorBuilder, }) => CatalogImplementation( id: id, protocolVersion: A2uiProtocolVersion.v1_0, @@ -75,6 +83,8 @@ CatalogImplementation templateCatalog({ c.value, primitives, onError, + media, + errorBuilder, ), node: node, props: props, @@ -93,6 +103,8 @@ class _Template { this.interface, this.primitives, this.onError, + this.media, + this.errorBuilder, ); final TemplateRegistry registry; @@ -101,6 +113,8 @@ class _Template { final TemplateInterface interface; final Map primitives; final TemplateErrorCallback? onError; + final MediaSource media; + final Widget Function(BuildContext context, ErrorNode node)? errorBuilder; /// The arguments that [props] give (requirement 5). TemplateArgs args(ComponentProps props) => @@ -203,6 +217,8 @@ class _TemplateComponentState extends State<_TemplateComponent> { runtime: _runtime, libraries: widget.template.primitives, onEvent: _onEvent, + media: widget.template.media, + errorBuilder: widget.template.errorBuilder, onError: switch (widget.template.onError) { final TemplateErrorCallback onError => (Object error) => onError( widget.node.componentId, diff --git a/craft/packages/a2ui_craft_renderer_flutter/test/template_catalog_test.dart b/craft/packages/a2ui_craft_renderer_flutter/test/template_catalog_test.dart index 76c522b6..982cb4a7 100644 --- a/craft/packages/a2ui_craft_renderer_flutter/test/template_catalog_test.dart +++ b/craft/packages/a2ui_craft_renderer_flutter/test/template_catalog_test.dart @@ -141,11 +141,16 @@ const String _templates = ''' export widget Broken = Column(children: [Nope()]); + export widget Media = Text(text: concat(a: "width ", b: media.width)); + export widget StoreMap = maps::Map(); '''; class _Harness { - _Harness() { + _Harness({ + MediaSource media = MediaSource.layout, + Widget Function(BuildContext context, ErrorNode node)? errorBuilder, + }) { registry ..setPrimitiveLibrary(coreLibrary, _core) ..setTemplateLibrary( @@ -167,6 +172,8 @@ class _Harness { primitives: {coreLibrary: _core}, functions: basicCatalog().functions.values.toList(), onError: (String id, Object error) => templateErrors.add((id, error)), + media: media, + errorBuilder: errorBuilder, ); processor = MessageProcessor( catalogs: [catalog, basicCatalog()], @@ -201,6 +208,7 @@ class _Harness { WidgetTester tester, List> components, { Map? data, + Widget Function(Widget surface)? wrap, }) async { addTearDown(processor.model.dispose); send('createSurface', { @@ -210,7 +218,9 @@ class _Harness { send('updateComponents', {'components': components}); await tester.pumpWidget( MaterialApp( - home: Scaffold(body: A2uiSurface(surface: surface)), + home: Scaffold( + body: (wrap ?? (Widget s) => s)(A2uiSurface(surface: surface)), + ), ), ); } @@ -229,6 +239,7 @@ void main() { 'Counter', 'Card', 'Broken', + 'Media', ]); expect( h.catalog.components['Card']!.schema.value, @@ -535,4 +546,128 @@ void main() { expect(h.templateErrors.single.$1, 'root'); expect(h.templateErrors.single.$2, isA()); }); + + testWidgets('template components size themselves inside intrinsic widgets', ( + WidgetTester tester, + ) async { + for (final MediaSource media in MediaSource.values) { + for (final bool width in [true, false]) { + final _Harness h = _Harness(media: media); + await h.pump( + tester, + >[ + { + 'id': 'root', + 'component': 'Counter', + 'title': 'Clicks', + }, + ], + wrap: (Widget surface) => Align( + alignment: Alignment.topLeft, + child: width + ? IntrinsicWidth(child: surface) + : IntrinsicHeight(child: surface), + ), + ); + final String reason = '${media.name} ${width ? 'width' : 'height'}'; + expect(tester.takeException(), isNull, reason: reason); + expect(find.text('Clicks: 0'), findsOneWidget, reason: reason); + final Size text = tester.getSize(find.text('Clicks: 0')); + final Size box = tester.getSize( + find.byType(width ? IntrinsicWidth : IntrinsicHeight), + ); + expect(text.width, greaterThan(0), reason: reason); + if (width) { + expect(box.width, greaterThanOrEqualTo(text.width), reason: reason); + expect(box.width, lessThan(400), reason: '$reason: not the window'); + } else { + expect( + box.height, + greaterThanOrEqualTo(2 * text.height), + reason: '$reason: the text and the button, not 0 px', + ); + expect(box.height, lessThan(200), reason: '$reason: not the window'); + } + await tester.pumpWidget(const SizedBox()); + } + } + }); + + testWidgets('a library registered again renders at once with fresh state', ( + WidgetTester tester, + ) async { + final _Harness h = _Harness(); + await h.pump(tester, >[ + {'id': 'root', 'component': 'Counter', 'title': 'x'}, + ]); + await tester.tap(find.byKey(const ValueKey('inc'))); + await tester.pump(); + expect(find.text('x: 1'), findsOneWidget); + + h.registry.setTemplateLibrary( + _main, + parseLibraryFile(_templates.replaceFirst('a: ": "', 'a: " = "')), + ); + await tester.pump(); + expect(find.text('x = 0'), findsOneWidget); + }); + + testWidgets('the first tap after a registration counts', ( + WidgetTester tester, + ) async { + final _Harness h = _Harness(); + await h.pump(tester, >[ + {'id': 'root', 'component': 'Counter', 'title': 'x'}, + ]); + await tester.tap(find.byKey(const ValueKey('inc'))); + await tester.pump(); + h.registry.setTemplateLibrary(_main, parseLibraryFile(_templates)); + await tester.pump(); + expect(find.text('x: 0'), findsOneWidget); + await tester.tap(find.byKey(const ValueKey('inc'))); + await tester.pump(); + expect(find.text('x: 1'), findsOneWidget); + }); + + testWidgets('a host builds the placeholder of a failed widget', ( + WidgetTester tester, + ) async { + final _Harness h = _Harness( + errorBuilder: (BuildContext context, ErrorNode node) => + Text('failed: ${node.kind.name}'), + ); + await h.pump(tester, >[ + {'id': 'root', 'component': 'Broken'}, + ]); + expect(find.text('failed: unknownFunction'), findsOneWidget); + expect(find.byType(ErrorWidget), findsNothing); + }); + + testWidgets('the catalog renders with its media source', ( + WidgetTester tester, + ) async { + tester.view + ..physicalSize = const Size(800, 600) + ..devicePixelRatio = 1; + addTearDown(tester.view.reset); + for (final (MediaSource media, String text) in <(MediaSource, String)>[ + (MediaSource.layout, 'width compact'), + (MediaSource.window, 'width medium'), + (MediaSource.host, 'width '), + ]) { + final _Harness h = _Harness(media: media); + await h.pump( + tester, + >[ + {'id': 'root', 'component': 'Media'}, + ], + wrap: (Widget surface) => Align( + alignment: Alignment.topLeft, + child: SizedBox(width: 300, height: 300, child: surface), + ), + ); + expect(find.text(text), findsOneWidget, reason: media.name); + await tester.pumpWidget(const SizedBox()); + } + }); }