Skip to content

feat(craft): add the Flutter adapter - #30

Open
innkuika wants to merge 2 commits into
craft/engine-runtimefrom
craft/engine-flutter
Open

innkuika wants to merge 2 commits into
craft/engine-runtimefrom
craft/engine-flutter

Conversation

@innkuika

Copy link
Copy Markdown
Contributor

Description

Adds craft/packages/a2ui_craft_flutter, the thin Flutter adapter for the Craft runtime. Stacked on #29.

  • CraftView renders a CraftRuntime's expansion tree with Flutter widgets. It forwards events to the host and reports expansion errors, setter failures and missing primitives. Error nodes render as a small placeholder.
  • PrimitiveWidgetLibrary / PrimitiveWidget: how a host provides Flutter implementations of primitives. PrimitiveArguments gives them evaluated values, children, handlers (null when a handler does nothing, so a control can be disabled) and builders.
  • Changes that arrive while Flutter is building are rendered after that frame; several of them become one re-expansion. Nothing is reported after the view is unmounted.
  • Tests: 14 widget tests using a tiny test-only primitive library. The real building blocks come separately.
  • The package has its own codebase blueprint. The runtime feature itself is specified and conformance-tested in the core (feat(craft): add the framework-independent runtime #29).

An independent review checked it, including mutations.

Pre-launch Checklist

One time:

For this PR:

  • I updated/added relevant documentation.
  • My code changes (if any) have tests.
  • License checks pass (python3 ./scripts/fix_licenses.py --check).
  • Format checks pass (./scripts/fix_format.sh --check).

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces the Flutter adapter for the Craft engine (a2ui_craft_flutter), adding the core CraftView widget, primitive widget definitions, and comprehensive widget tests. The review feedback highlights a potential crash in CraftView where a null-check operator on widget.onError could fail if the callback is updated to null before the post-frame callback executes, as well as an opportunity to optimize event handling by avoiding a no-op closure allocation when widget.onEvent is null.

Comment on lines +143 to +147
SchedulerBinding.instance.addPostFrameCallback((Duration _) {
final List<Object> errors = List<Object>.of(_pendingErrors);
_pendingErrors.clear();
if (mounted) errors.forEach(widget.onError!);
});

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

If widget.onError is updated to null (via didUpdateWidget) after a post-frame callback has been scheduled but before it executes, calling widget.onError! will throw a NullCheckError and crash the application.

To prevent this, safely capture or check widget.onError before invoking it.

Suggested change
SchedulerBinding.instance.addPostFrameCallback((Duration _) {
final List<Object> errors = List<Object>.of(_pendingErrors);
_pendingErrors.clear();
if (mounted) errors.forEach(widget.onError!);
});
SchedulerBinding.instance.addPostFrameCallback((Duration _) {
final List<Object> errors = List<Object>.of(_pendingErrors);
_pendingErrors.clear();
if (mounted) {
final onError = widget.onError;
if (onError != null) {
errors.forEach(onError);
}
}
});

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch, reproduced (a pending error plus a rebuild with onError: null throws). Fixed in the latest push by reading widget.onError when the callback runs, with a regression test.


void _fire(Object handler, Map<String, Object?> arguments) {
final FireResult result = widget.runtime.fire(handler, arguments);
result.events.forEach(widget.onEvent ?? (HostEvent _) {});

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Avoid creating and invoking a no-op closure (HostEvent _) {} for every event when widget.onEvent is null. Instead, conditionally invoke widget.onEvent only if it is non-null.

    final onEvent = widget.onEvent;
    if (onEvent != null) {
      result.events.forEach(onEvent);
    }

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done alongside the onError fix.

@ditman ditman left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 Clean, minimal Flutter adapter — separating expansion/state into a2ui_craft while keeping CraftView as a thin rendering shell with post-frame coalescing and PrimitiveWidgetLibrary doubling as a PrimitiveLibrary is a really nice design.

A few items to address before (or cleanly alongside) landing:

  1. Missing mounted guard in _CraftViewState._changed() (craft_view.dart): CraftRuntime._notify() iterates a snapshot copy of _listeners. If another listener disposes CraftView during notification, _changed() is still invoked and calls setState(_expand) on an unmounted State.
  2. Unkeyed _NodeWidget wrapper traps primitive keys (craft_view.dart): _NodeWidget has key: null, so keys placed by primitives on their returned widgets (like Button's ValueKey in craft_view_test.dart) are invisible to sibling reconciliation in Column/Row/Stack. Inserting/reordering items in ...for/...if lists will recreate stateful primitives (TextField focus/cursor, scroll controllers, animations).
  3. Post-stack barrel tightening reminder (lib/a2ui_craft_flutter.dart): Per our agreement on #23, please include a2ui_craft_flutter.dart when switching public barrels to explicit show lists so public API changes stay easy to track.
  4. Minor error/lifecycle nits: MissingPrimitiveWidget bypasses errorBuilder (always rendering ErrorWidget), and swapping widget.runtime in didUpdateWidget while a post-frame expansion is already scheduled causes one redundant re-expansion.

(Noted that same-frame superseded expansion error filtering and live registry refresh are already queued in #39, so I left those out of this review.)

Comment on lines +20 to +21
export 'src/craft_view.dart';
export 'src/primitive_widgets.dart';

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reminder for the post-stack barrel-tightening pass agreed in #23: please include lib/a2ui_craft_flutter.dart when switching public barrels to explicit show lists so public API additions are easy to track:

export 'src/craft_view.dart' show CraftView, MissingPrimitiveWidget;
export 'src/primitive_widgets.dart'
    show
        PrimitiveArguments,
        PrimitiveWidget,
        PrimitiveWidgetBuilder,
        PrimitiveWidgetLibrary;

Comment on lines +119 to +124
void _changed() {
if (SchedulerBinding.instance.schedulerPhase !=
SchedulerPhase.persistentCallbacks) {
setState(_expand);
return;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 Please add if (!mounted) return; at the top of _changed().

CraftRuntime._notify() iterates List.of(_listeners) (a snapshot). If an earlier listener on the same runtime unmounts CraftView during notification (e.g. navigating away on a state change), dispose() removes _changed from _listeners too late for the in-flight snapshot, so _changed() is still called after disposal and setState(_expand) throws FlutterError: setState() called after dispose().

Drop-in regression test for craft/packages/a2ui_craft_flutter/test/craft_view_test.dart:

  testWidgets('unmounting during runtime notification does not call setState', (
    WidgetTester tester,
  ) async {
    final _Harness h = _Harness(
      '''
      import core;
      widget root = Text(text: data.v);
    ''',
      data: <String, Object?>{'v': 'a'},
    );
    bool show = true;
    late StateSetter setHostState;
    h.runtime.addListener(() {
      if (!show) return;
      setHostState(() => show = false);
      tester.binding.buildOwner!
        ..buildScope(tester.binding.rootElement!)
        ..finalizeTree();
    });
    await tester.pumpWidget(
      StatefulBuilder(
        builder: (BuildContext context, StateSetter setState) {
          setHostState = setState;
          return show ? h.view() : const SizedBox();
        },
      ),
    );
    expect(
      () => h.runtime.data = <String, Object?>{'v': 'b'},
      returnsNormally,
    );
  });

Comment on lines +172 to +174
Widget _render(Object node) => switch (node) {
WidgetNode() => _NodeWidget(node: node, view: this),
ErrorNode() => Builder(

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 Because _NodeWidget has key: null, Flutter reconciles sibling children of Column/Row/Stack strictly by index rather than by any Key a primitive puts on its returned widget (for example Button's ValueKey in craft_view_test.dart:48-51).

When a ...for loop or ...if conditional inserts, removes, or reorders items, Flutter matches each shifted _NodeWidget to the wrong previous element and destroys/recreates stateful primitive widgets underneath (losing TextField focus/IME state, scroll offsets, or animations). Before real primitives land, worth deciding whether to lift a Key onto _NodeWidget (e.g. via a key convention or PrimitiveWidget key extractor) or pass BuildContext through PrimitiveArguments so primitives aren't wrapped in an unkeyed widget.

Drop-in regression test for craft/packages/a2ui_craft_flutter/test/craft_view_test.dart:

class _CounterBox extends StatefulWidget {
  const _CounterBox({super.key, required this.id});

  final String id;

  @override
  State<_CounterBox> createState() => _CounterBoxState();
}

class _CounterBoxState extends State<_CounterBox> {
  int count = 0;

  @override
  Widget build(BuildContext context) => GestureDetector(
    onTap: () => setState(() => count += 1),
    child: Text('${widget.id}:$count'),
  );
}
  testWidgets('prepending a loop item preserves keyed primitive state', (
    WidgetTester tester,
  ) async {
    final PrimitiveWidgetLibrary libs = PrimitiveWidgetLibrary(
      <String, PrimitiveWidget>{
        ..._testWidgets.widgets,
        'CounterBox': PrimitiveWidget(
          (BuildContext context, PrimitiveArguments args) {
            final String id = args.value<String>('id') ?? '';
            return _CounterBox(key: ValueKey<String>(id), id: id);
          },
        ),
      },
    );
    final TemplateRegistry registry = TemplateRegistry()
      ..setPrimitiveLibrary(coreLibrary, libs)
      ..setTemplateLibrary(
        _main,
        parseLibraryFile('''
          import core;
          widget root = Column(children: [
            ...for item in data.items: CounterBox(id: item),
          ]);
        '''),
      );
    final CraftRuntime runtime = CraftRuntime(
      registry,
      library: _main,
      widget: 'root',
      data: <String, Object?>{
        'items': <Object?>['b'],
      },
    );
    await tester.pumpWidget(
      Directionality(
        textDirection: TextDirection.ltr,
        child: CraftView(
          runtime: runtime,
          libraries: <LibraryName, PrimitiveWidgetLibrary>{coreLibrary: libs},
        ),
      ),
    );
    await tester.tap(find.byKey(const ValueKey<String>('b')));
    await tester.pump();
    expect(find.text('b:1'), findsOneWidget);

    runtime.data = <String, Object?>{
      'items': <Object?>['a', 'b'],
    };
    await tester.pump();
    expect(find.text('a:0'), findsOneWidget);
    expect(find.text('b:1'), findsOneWidget);
  });

Comment on lines +202 to +205
if (primitive == null) {
view._reportOnce('missing ${node.path}', MissingPrimitiveWidget(node));
return _placeholder(MissingPrimitiveWidget(node).toString());
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 Unlike ErrorNode (lines 174-178), a missing primitive unconditionally renders _placeholder(...) (ErrorWidget), bypassing widget.errorBuilder. In production hosts that pass a custom errorBuilder specifically to avoid Flutter's ErrorWidget box, a missing primitive still shows ErrorWidget—worth considering a customization hook (or generalizing the placeholder callback) so hosts can handle both consistently.

Comment on lines +95 to +102
void didUpdateWidget(CraftView oldWidget) {
super.didUpdateWidget(oldWidget);
if (!identical(oldWidget.runtime, widget.runtime)) {
oldWidget.runtime.removeListener(_changed);
widget.runtime.addListener(_changed);
_expand();
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 Minor edge case: if oldWidget.runtime triggered _changed() during persistentCallbacks (_expansionScheduled = true), and didUpdateWidget swaps in a new widget.runtime in the same frame and calls _expand(), the already-scheduled post-frame callback still runs and calls setState(_expand) a second time on the new runtime. Tracking a generation counter (or clearing a dirty flag) avoids the redundant expansion.

Drop-in regression test for craft/packages/a2ui_craft_flutter/test/craft_view_test.dart:

  testWidgets('swapping runtime cancels a pending post-frame expansion', (
    WidgetTester tester,
  ) async {
    final _Harness h1 = _Harness(
      '''
      import core;
      widget root = Text(text: data.v);
    ''',
      data: <String, Object?>{'v': '1'},
    );
    int h2Expansions = 0;
    final _Harness h2 = _Harness('''
      import core;
      import t;
      widget root = Text(text: t::count());
    ''');
    h2.registry.setHostFunctions(
      const LibraryName(<String>['t']),
      <String, LocalFunction>{
        'count': LocalFunction(
          arguments: const <String, FunctionArgType>{},
          implementation: (DynamicMap arguments) => '#${h2Expansions += 1}',
        ),
      },
    );
    Widget page(CraftRuntime runtime, {bool mutateOld = false}) =>
        Directionality(
          textDirection: TextDirection.ltr,
          child: Column(
            children: <Widget>[
              Builder(
                builder: (BuildContext context) {
                  if (mutateOld) h1.runtime.data = <String, Object?>{'v': '2'};
                  return const SizedBox();
                },
              ),
              CraftView(
                runtime: runtime,
                libraries: <LibraryName, PrimitiveWidgetLibrary>{
                  coreLibrary: _testWidgets,
                },
              ),
            ],
          ),
        );
    await tester.pumpWidget(page(h1.runtime));
    await tester.pumpWidget(page(h2.runtime, mutateOld: true));
    await tester.pump();
    expect(h2Expansions, 1);
  });

@innkuika
innkuika force-pushed the craft/engine-flutter branch 2 times, most recently from 0bb773b to eb98e16 Compare December 3, 2026 02:07
innkuika and others added 2 commits December 3, 2026 10:59
Adds the craft_runtime feature: expanding a template, with its
arguments, data and local state, into a tree of primitive calls, and
firing the handlers in that tree.

- craft/blueprints/features/craft_runtime.blueprint.md: the expansion
  and its canonical JSON form (primitive, error and builder nodes,
  handler nodes, paths), primitive and template calls (arguments
  evaluated on first read in the scope of the call), references, loops
  and `...if`, switches, handlers (event, set state, `call`, host
  handlers, handler lists), firing, local state (per path and template;
  kept across data updates, reset when the template's library is
  registered again), widget builders, errors as placeholder nodes at the
  innermost widget, and updates.
- craft/conformance/craft/craft_runtime.yaml: 67 cases, each an initial
  expansion and steps (fire a value at a path, replace data or
  arguments, register a library again, expand a builder's output),
  checking the canonical tree, states, errors and emitted events.
- packages/a2ui_craft: lib/src/expansion.dart (nodes and canonical form)
  and lib/src/runtime.dart (CraftRuntime); evaluator.dart now shares
  checkCallArguments and invokeFunction with the runtime, and
  TemplateRegistry counts each library name's registrations (generation),
  so state resets even when the same library object is registered again.
  Unit tests cover nodes only the binary format can hold, host input,
  reloads, notifications and snapshots.
- craft_functions.blueprint.md: says that no feature defines theme
  references yet; the module layer table describes the runtime's output.
- Conformance: the expand_template action (runtime_engine.dart, which
  later suites share) and the F-CRAFT-RT-01 to 13 feature IDs.

The code is new. Its semantics follow RFW 2.0.0's runtime and the Craft
prototype's runtime, including the prototype's fixes: handler lists keep
host callbacks, state survives a data update and resets on a template
reload, and a null list item is absent. Unlike both, the runtime builds no
widgets; a framework adapter renders the expansion.

Co-authored-by: Yegor <yegor.jbanov@gmail.com>
Adds craft/packages/a2ui_craft_flutter, which renders the expansion of a
CraftRuntime (package:a2ui_craft) with Flutter widgets:

- PrimitiveWidgetLibrary / PrimitiveWidget: the host's primitives as
  Flutter widget builders with their metadata; the same object is
  registered in the TemplateRegistry. PrimitiveArguments gives a builder
  its values, children, handlers (null when not runnable, so controls can
  be disabled; value handlers fire with {value: v}) and builder outputs.
- CraftView: renders the current expansion, expands again when the
  runtime notifies a change (once after the frame for any number of
  changes during a build, so it never rebuilds during a build), stops
  listening when disposed, fires handlers, forwards events to onEvent, and
  reports expansion errors, firing errors and primitives without a widget
  to onError (errors found while rendering once per expansion, nothing
  once the view is gone); error nodes render as a small placeholder.
- Widget tests with a tiny test-only primitive library.
- craft/blueprints/codebases/dart/a2ui_craft_flutter/codebase.blueprint.md.

New code; it replaces the prototype's Flutter runtime, whose expansion,
state and event handling now live in the framework-independent core.
@innkuika
innkuika force-pushed the craft/engine-flutter branch from eb98e16 to 7cc4392 Compare December 3, 2026 19:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants