Repository navigation
Conversation
There was a problem hiding this comment.
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.
| SchedulerBinding.instance.addPostFrameCallback((Duration _) { | ||
| final List<Object> errors = List<Object>.of(_pendingErrors); | ||
| _pendingErrors.clear(); | ||
| if (mounted) errors.forEach(widget.onError!); | ||
| }); |
There was a problem hiding this comment.
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.
| 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); | |
| } | |
| } | |
| }); |
There was a problem hiding this comment.
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 _) {}); |
There was a problem hiding this comment.
There was a problem hiding this comment.
Done alongside the onError fix.
4ec292c to
93a7bd6
Compare
93a7bd6 to
71ef411
Compare
71ef411 to
6465aaa
Compare
6465aaa to
d0be621
Compare
d0be621 to
5852866
Compare
ditman
left a comment
There was a problem hiding this comment.
🤖 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:
- Missing
mountedguard in_CraftViewState._changed()(craft_view.dart):CraftRuntime._notify()iterates a snapshot copy of_listeners. If another listener disposesCraftViewduring notification,_changed()is still invoked and callssetState(_expand)on an unmountedState. - Unkeyed
_NodeWidgetwrapper traps primitive keys (craft_view.dart):_NodeWidgethaskey: null, so keys placed by primitives on their returned widgets (likeButton'sValueKeyincraft_view_test.dart) are invisible to sibling reconciliation inColumn/Row/Stack. Inserting/reordering items in...for/...iflists will recreate stateful primitives (TextFieldfocus/cursor, scroll controllers, animations). - Post-stack barrel tightening reminder (
lib/a2ui_craft_flutter.dart): Per our agreement on #23, please includea2ui_craft_flutter.dartwhen switching public barrels to explicitshowlists so public API changes stay easy to track. - Minor error/lifecycle nits:
MissingPrimitiveWidgetbypasseserrorBuilder(always renderingErrorWidget), and swappingwidget.runtimeindidUpdateWidgetwhile 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.)
| export 'src/craft_view.dart'; | ||
| export 'src/primitive_widgets.dart'; |
There was a problem hiding this comment.
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;| void _changed() { | ||
| if (SchedulerBinding.instance.schedulerPhase != | ||
| SchedulerPhase.persistentCallbacks) { | ||
| setState(_expand); | ||
| return; | ||
| } |
There was a problem hiding this comment.
🤖 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,
);
});| Widget _render(Object node) => switch (node) { | ||
| WidgetNode() => _NodeWidget(node: node, view: this), | ||
| ErrorNode() => Builder( |
There was a problem hiding this comment.
🤖 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);
});| if (primitive == null) { | ||
| view._reportOnce('missing ${node.path}', MissingPrimitiveWidget(node)); | ||
| return _placeholder(MissingPrimitiveWidget(node).toString()); | ||
| } |
There was a problem hiding this comment.
🤖 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.
| void didUpdateWidget(CraftView oldWidget) { | ||
| super.didUpdateWidget(oldWidget); | ||
| if (!identical(oldWidget.runtime, widget.runtime)) { | ||
| oldWidget.runtime.removeListener(_changed); | ||
| widget.runtime.addListener(_changed); | ||
| _expand(); | ||
| } | ||
| } |
There was a problem hiding this comment.
🤖 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);
});0bb773b to
eb98e16
Compare
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.
eb98e16 to
7cc4392
Compare
Description
Adds
craft/packages/a2ui_craft_flutter, the thin Flutter adapter for the Craft runtime. Stacked on #29.CraftViewrenders aCraftRuntime'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.PrimitiveArgumentsgives them evaluated values, children, handlers (null when a handler does nothing, so a control can be disabled) and builders.An independent review checked it, including mutations.
Pre-launch Checklist
One time:
For this PR:
python3 ./scripts/fix_licenses.py --check)../scripts/fix_format.sh --check).