diff --git a/packages/genui/CHANGELOG.md b/packages/genui/CHANGELOG.md index c168f36ba..72880c452 100644 --- a/packages/genui/CHANGELOG.md +++ b/packages/genui/CHANGELOG.md @@ -1,5 +1,13 @@ # [genui](https://pub.dev/packages/genui) Changelog +## 0.10.5 + +- **Fix**: Resolve validation checks and preserve error messages across basic catalog components. + - Recursively evaluate `List` arguments in `DataContext._evaluateStream` so logical functions (`and`, `or`) receive resolved values. + - Remove invalid `'functionCall'` envelope from `checksToExpression` and support tolerant unwrapping in `_evaluateStream`. + - Align truthiness evaluation in `isTruthy` across primitives, data model objects, and structured `ValidationResult` objects, while warning on malformed expressions or missing functions. + - Migrate `CheckBox`, `Slider`, and `ChoicePicker` to `ValidationHelper.validateStream` to evaluate rules individually and display authored error messages. + ## 0.10.4 - **Fix**: `Image` now takes the catalog's `description` property and announces it. The property is what the basic diff --git a/packages/genui/lib/src/catalog/basic_catalog_widgets/check_box.dart b/packages/genui/lib/src/catalog/basic_catalog_widgets/check_box.dart index 7fd2e308b..f8809346e 100644 --- a/packages/genui/lib/src/catalog/basic_catalog_widgets/check_box.dart +++ b/packages/genui/lib/src/catalog/basic_catalog_widgets/check_box.dart @@ -8,9 +8,9 @@ import 'package:json_schema_builder/json_schema_builder.dart'; import '../../model/a2ui_schemas.dart'; import '../../model/catalog_item.dart'; import '../../model/data_model.dart'; +import '../../model/validation_helper.dart'; import '../../primitives/simple_items.dart'; import '../../widgets/widget_utilities.dart'; -import 'widget_helpers.dart'; final _schema = S.object( description: 'A selectable checkbox used for boolean toggles with a label.', @@ -61,14 +61,14 @@ final checkBox = CatalogItem( value: checkBoxData.label, builder: (context, label) { // Wrap the checkbox in validation - return StreamBuilder( - stream: itemContext.dataContext.evaluateConditionStream( - checksToExpression(checkBoxData.checks), + return StreamBuilder( + stream: ValidationHelper.validateStream( + checkBoxData.checks, + itemContext.dataContext, ), - initialData: true, builder: (context, snapshot) { - final bool isValid = snapshot.data ?? true; - final bool isError = !isValid; + final String? errorMessage = snapshot.data; + final isError = errorMessage != null; return ListTileTheme.merge( child: BoundBool( @@ -92,9 +92,9 @@ final checkBox = CatalogItem( ); } }, - subtitle: isError + subtitle: errorMessage != null ? Text( - 'Invalid value', + errorMessage, style: TextStyle( color: Theme.of(context).colorScheme.error, fontSize: 12, diff --git a/packages/genui/lib/src/catalog/basic_catalog_widgets/choice_picker.dart b/packages/genui/lib/src/catalog/basic_catalog_widgets/choice_picker.dart index b995f9fd0..94088b1fa 100644 --- a/packages/genui/lib/src/catalog/basic_catalog_widgets/choice_picker.dart +++ b/packages/genui/lib/src/catalog/basic_catalog_widgets/choice_picker.dart @@ -8,9 +8,9 @@ import 'package:json_schema_builder/json_schema_builder.dart'; import '../../model/a2ui_schemas.dart'; import '../../model/catalog_item.dart'; import '../../model/data_model.dart'; +import '../../model/validation_helper.dart'; import '../../primitives/simple_items.dart'; import '../../widgets/widget_utilities.dart'; -import 'widget_helpers.dart'; final _schema = S.object( description: @@ -85,14 +85,14 @@ final choicePicker = CatalogItem( final isChips = data.displayStyle == 'chips'; // Wrap the picker in validation - return StreamBuilder( - stream: itemContext.dataContext.evaluateConditionStream( - checksToExpression(data.checks), + return StreamBuilder( + stream: ValidationHelper.validateStream( + data.checks, + itemContext.dataContext, ), - initialData: true, builder: (context, snapshot) { - final bool isValid = snapshot.data ?? true; - final bool isError = !isValid; + final String? errorMessage = snapshot.data; + final isError = errorMessage != null; return BoundList( dataContext: itemContext.dataContext, @@ -121,7 +121,7 @@ final choicePicker = CatalogItem( Padding( padding: const EdgeInsets.only(left: 16.0, top: 4.0), child: Text( - 'Invalid selection', + errorMessage, style: TextStyle( color: Theme.of(context).colorScheme.error, fontSize: 12, diff --git a/packages/genui/lib/src/catalog/basic_catalog_widgets/slider.dart b/packages/genui/lib/src/catalog/basic_catalog_widgets/slider.dart index 33e290669..319374a33 100644 --- a/packages/genui/lib/src/catalog/basic_catalog_widgets/slider.dart +++ b/packages/genui/lib/src/catalog/basic_catalog_widgets/slider.dart @@ -8,9 +8,9 @@ import 'package:json_schema_builder/json_schema_builder.dart'; import '../../model/a2ui_schemas.dart'; import '../../model/catalog_item.dart'; import '../../model/data_model.dart'; +import '../../model/validation_helper.dart'; import '../../primitives/simple_items.dart'; import '../../widgets/widget_utilities.dart'; -import 'widget_helpers.dart'; final _schema = S.object( description: 'A slider for selecting a value from a range.', @@ -116,14 +116,14 @@ final slider = CatalogItem( dataContext: itemContext.dataContext, value: sliderData.label, builder: (context, label) { - return StreamBuilder( - stream: itemContext.dataContext.evaluateConditionStream( - checksToExpression(sliderData.checks), + return StreamBuilder( + stream: ValidationHelper.validateStream( + sliderData.checks, + itemContext.dataContext, ), - initialData: true, builder: (context, snapshot) { - final bool isValid = snapshot.data ?? true; - final bool isError = !isValid; + final String? errorMessage = snapshot.data; + final isError = errorMessage != null; final List children = [ if (label != null) @@ -142,7 +142,7 @@ final slider = CatalogItem( Padding( padding: const EdgeInsets.only(left: 16.0, top: 4.0), child: Text( - 'Invalid value', + errorMessage, style: TextStyle( color: Theme.of(context).colorScheme.error, fontSize: 12, diff --git a/packages/genui/lib/src/catalog/basic_catalog_widgets/widget_helpers.dart b/packages/genui/lib/src/catalog/basic_catalog_widgets/widget_helpers.dart index c843fae3c..db6325add 100644 --- a/packages/genui/lib/src/catalog/basic_catalog_widgets/widget_helpers.dart +++ b/packages/genui/lib/src/catalog/basic_catalog_widgets/widget_helpers.dart @@ -147,11 +147,20 @@ Object? checksToExpression(List? checks) { return true; } + final List conditions = checks + .map((c) => c['condition']) + .where((c) => c != null) + .toList(); + if (conditions.isEmpty) { + return true; + } + if (conditions.length == 1) { + return conditions.first; + } + // Combine all checks into a single 'and' condition return { - 'functionCall': { - 'call': 'and', - 'args': {'values': checks.map((c) => c['condition']).toList()}, - }, + 'call': 'and', + 'args': {'values': conditions}, }; } diff --git a/packages/genui/lib/src/catalog/basic_functions.dart b/packages/genui/lib/src/catalog/basic_functions.dart index 6013ab261..fa61653e8 100644 --- a/packages/genui/lib/src/catalog/basic_functions.dart +++ b/packages/genui/lib/src/catalog/basic_functions.dart @@ -9,6 +9,7 @@ import 'package:url_launcher/url_launcher.dart'; import '../functions/format_string.dart'; import '../model/a2ui_schemas.dart'; import '../model/client_function.dart'; +import '../model/data_model.dart'; import '../primitives/simple_items.dart'; // ignore: avoid_classes_with_only_static_members @@ -48,13 +49,6 @@ class BasicFunctions { ]; } -/// Helper to check for truthiness. -bool _isTruthy(Object? value) { - if (value is bool) return value; - if (value == null) return false; - return true; -} - /// Checks if all values in a list are truthy. class AndFunction extends SynchronousClientFunction { const AndFunction(); @@ -78,7 +72,7 @@ class AndFunction extends SynchronousClientFunction { final Object? values = args['values']; if (values is! List) return false; for (final Object? element in values) { - if (!_isTruthy(element)) return false; + if (!isTruthy(element)) return false; } return true; } @@ -108,7 +102,7 @@ class OrFunction extends SynchronousClientFunction { final Object? values = args['values']; if (values is! List) return false; for (final Object? element in values) { - if (_isTruthy(element)) return true; + if (isTruthy(element)) return true; } return false; } @@ -134,7 +128,7 @@ class NotFunction extends SynchronousClientFunction { @override Object? executeSync(JsonMap args, ExecutionContext _) { if (!args.containsKey('value')) return false; - return !_isTruthy(args['value']); + return !isTruthy(args['value']); } } diff --git a/packages/genui/lib/src/model/data_model.dart b/packages/genui/lib/src/model/data_model.dart index 982b2bace..7034de67f 100644 --- a/packages/genui/lib/src/model/data_model.dart +++ b/packages/genui/lib/src/model/data_model.dart @@ -115,6 +115,16 @@ class DataContext implements cf.ExecutionContext { if (value.containsKey('call')) { return _evaluateFunctionCall(value as JsonMap); } + if (value.containsKey('functionCall') && value['functionCall'] is Map) { + return _evaluateStream(value['functionCall']); + } + } + if (value is List) { + if (value.isEmpty) return Stream.value([]); + final List> itemStreams = value + .map(_evaluateStream) + .toList(); + return itemStreams.combineLatestAll(); } if (value is Stream) return value.cast(); return Stream.value(value); @@ -123,6 +133,9 @@ class DataContext implements cf.ExecutionContext { Stream _evaluateFunctionCall(JsonMap callDefinition) { final name = callDefinition['call'] as String?; if (name == null) { + genUiLogger.warning( + 'Function call missing "call" property: $callDefinition', + ); return Stream.value(null); } @@ -167,12 +180,33 @@ class DataContext implements cf.ExecutionContext { if (condition == null) return Stream.value(false); if (condition is bool) return Stream.value(condition); + if (condition is Map && + !condition.containsKey('path') && + !condition.containsKey('call') && + !condition.containsKey('functionCall')) { + genUiLogger.warning('Invalid condition expression: $condition'); + return Stream.value(false); + } + final Stream resultStream = _evaluateStream(condition); - return resultStream.map((v) { - if (v is bool) return v; - return v != null; - }); + return resultStream.map(isTruthy); + } +} + +/// Helper to determine truthiness according to A2UI expression semantics. +bool isTruthy(Object? value) { + if (value is bool) return value; + if (value == null) return false; + if (value is String) return value.isNotEmpty; + if (value is num) return value != 0 && !value.isNaN; + if (value is List) return value.isNotEmpty; + if (value is Map) { + if (value.containsKey('valid') && value['valid'] is bool) { + return value['valid'] as bool; + } + return value.isNotEmpty; } + return false; } /// Resolves a context map definition against a [DataContext]. diff --git a/packages/genui/pubspec.yaml b/packages/genui/pubspec.yaml index 6f10fe3bf..f4ae0019a 100644 --- a/packages/genui/pubspec.yaml +++ b/packages/genui/pubspec.yaml @@ -4,7 +4,7 @@ name: genui description: Generates and displays generative user interfaces (GenUI) in Flutter using AI. -version: 0.10.4 +version: 0.10.5 homepage: https://github.com/flutter/genui/tree/main/packages/genui license: BSD-3-Clause issue_tracker: https://github.com/flutter/genui/issues diff --git a/packages/genui/test/catalog/core_widgets/check_box_test.dart b/packages/genui/test/catalog/core_widgets/check_box_test.dart index 70f187d70..ab203b159 100644 --- a/packages/genui/test/catalog/core_widgets/check_box_test.dart +++ b/packages/genui/test/catalog/core_widgets/check_box_test.dart @@ -164,4 +164,69 @@ void main() { isTrue, ); }); + + testWidgets('CheckBox validation checks show error message when failing', ( + WidgetTester tester, + ) async { + final surfaceController = SurfaceController( + catalogs: [BasicCatalogItems.asCatalog()], + ); + addTearDown(surfaceController.dispose); + const surfaceId = 'validationTest'; + surfaceController.handleMessage( + updateDataModel( + surfaceId: surfaceId, + path: DataPath('/accepted'), + value: false, + ), + ); + + final List components = [ + component( + id: 'root', + type: 'CheckBox', + properties: { + 'label': 'I agree', + 'value': {'path': '/accepted'}, + 'checks': [ + { + 'message': 'You must accept the terms', + 'condition': {'path': '/accepted'}, + }, + ], + }, + ), + ]; + + surfaceController.handleMessage( + updateComponents(surfaceId: surfaceId, components: components), + ); + surfaceController.handleMessage( + createSurface(surfaceId: surfaceId, catalogId: basicCatalogId), + ); + + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Surface( + surfaceContext: surfaceController.contextFor(surfaceId), + ), + ), + ), + ); + await tester.pumpAndSettle(); + + expect(find.text('You must accept the terms'), findsOneWidget); + + surfaceController.handleMessage( + updateDataModel( + surfaceId: surfaceId, + path: DataPath('/accepted'), + value: true, + ), + ); + await tester.pumpAndSettle(); + + expect(find.text('You must accept the terms'), findsNothing); + }); } diff --git a/packages/genui/test/catalog/core_widgets/choice_picker_test.dart b/packages/genui/test/catalog/core_widgets/choice_picker_test.dart index 7bd8820c2..69d841d29 100644 --- a/packages/genui/test/catalog/core_widgets/choice_picker_test.dart +++ b/packages/genui/test/catalog/core_widgets/choice_picker_test.dart @@ -383,4 +383,80 @@ void main() { ); expect(checkboxNumber.value, false); // 123 does not match option1 }); + + testWidgets( + 'ChoicePicker validation checks show error message when failing', + (WidgetTester tester) async { + final surfaceController = SurfaceController( + catalogs: [BasicCatalogItems.asCatalog()], + ); + addTearDown(surfaceController.dispose); + const surfaceId = 'validationTest'; + surfaceController.handleMessage( + updateDataModel( + surfaceId: surfaceId, + path: DataPath('/selected'), + value: '', + ), + ); + + final List components = [ + component( + id: 'root', + type: 'ChoicePicker', + properties: { + 'label': 'Pick one', + 'variant': 'mutuallyExclusive', + 'options': [ + {'label': 'A', 'value': 'a'}, + {'label': 'B', 'value': 'b'}, + ], + 'value': {'path': '/selected'}, + 'checks': [ + { + 'message': 'Selection required', + 'condition': { + 'call': 'required', + 'args': { + 'value': {'path': '/selected'}, + }, + }, + }, + ], + }, + ), + ]; + + surfaceController.handleMessage( + updateComponents(surfaceId: surfaceId, components: components), + ); + surfaceController.handleMessage( + createSurface(surfaceId: surfaceId, catalogId: basicCatalogId), + ); + + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Surface( + surfaceContext: surfaceController.contextFor(surfaceId), + ), + ), + ), + ); + await tester.pumpAndSettle(); + + expect(find.text('Selection required'), findsOneWidget); + + surfaceController.handleMessage( + updateDataModel( + surfaceId: surfaceId, + path: DataPath('/selected'), + value: 'a', + ), + ); + await tester.pumpAndSettle(); + + expect(find.text('Selection required'), findsNothing); + }, + ); } diff --git a/packages/genui/test/catalog/core_widgets/slider_test.dart b/packages/genui/test/catalog/core_widgets/slider_test.dart index 48e5ec1cb..97b39136c 100644 --- a/packages/genui/test/catalog/core_widgets/slider_test.dart +++ b/packages/genui/test/catalog/core_widgets/slider_test.dart @@ -101,4 +101,67 @@ void main() { expect(find.text('Volume'), findsOneWidget); }); + + testWidgets('Slider validation checks show error message when failing', ( + WidgetTester tester, + ) async { + final surfaceController = SurfaceController( + catalogs: [BasicCatalogItems.asCatalog()], + ); + addTearDown(surfaceController.dispose); + const surfaceId = 'validationTest'; + surfaceController.handleMessage( + updateDataModel(surfaceId: surfaceId, path: DataPath('/val'), value: 0.2), + ); + + final List components = [ + component( + id: 'root', + type: 'Slider', + properties: { + 'label': 'Volume', + 'value': {'path': '/val'}, + 'checks': [ + { + 'message': 'Must be at least 0.5', + 'condition': { + 'call': 'numeric', + 'args': { + 'value': {'path': '/val'}, + 'min': 0.5, + }, + }, + }, + ], + }, + ), + ]; + + surfaceController.handleMessage( + updateComponents(surfaceId: surfaceId, components: components), + ); + surfaceController.handleMessage( + createSurface(surfaceId: surfaceId, catalogId: basicCatalogId), + ); + + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Surface( + surfaceContext: surfaceController.contextFor(surfaceId), + ), + ), + ), + ); + await tester.pumpAndSettle(); + + expect(find.text('Must be at least 0.5'), findsOneWidget); + + surfaceController.handleMessage( + updateDataModel(surfaceId: surfaceId, path: DataPath('/val'), value: 0.8), + ); + await tester.pumpAndSettle(); + + expect(find.text('Must be at least 0.5'), findsNothing); + }); } diff --git a/packages/genui/test/model/data_model_test.dart b/packages/genui/test/model/data_model_test.dart index 76003ced2..799341bd1 100644 --- a/packages/genui/test/model/data_model_test.dart +++ b/packages/genui/test/model/data_model_test.dart @@ -6,8 +6,11 @@ import 'dart:async'; import 'package:flutter/foundation.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:genui/src/catalog/basic_catalog.dart'; +import 'package:genui/src/catalog/basic_catalog_widgets/widget_helpers.dart'; import 'package:genui/src/model/data_model.dart'; import 'package:genui/src/primitives/logging.dart'; +import 'package:genui/src/primitives/simple_items.dart'; import 'package:logging/logging.dart'; void main() { @@ -400,14 +403,159 @@ void main() { expect(await stream.first, isTrue); }); + test('evaluateConditionStream treats non-null non-bool objects as true ' + 'only if truthy', () async { + dataModel.update(DataPath('/str'), 'hello'); + final condition = {'path': '/str'}; + final Stream stream = context.evaluateConditionStream(condition); + expect(await stream.first, isTrue); // 'hello' is non-empty + + dataModel.update(DataPath('/str'), ''); + expect(await context.evaluateConditionStream(condition).first, isFalse); + + // Map truthiness: non-empty map is true, empty map is false + dataModel.update(DataPath('/user'), {'name': 'Ada'}); + final userCondition = {'path': '/user'}; + expect( + await context.evaluateConditionStream(userCondition).first, + isTrue, + ); + + dataModel.update(DataPath('/user'), {}); + expect( + await context.evaluateConditionStream(userCondition).first, + isFalse, + ); + + // ValidationResult map: valid flag determines truthiness + dataModel.update(DataPath('/valResult'), {'valid': true}); + final valResultCondition = {'path': '/valResult'}; + expect( + await context.evaluateConditionStream(valResultCondition).first, + isTrue, + ); + + dataModel.update(DataPath('/valResult'), { + 'valid': false, + 'message': 'err', + }); + expect( + await context.evaluateConditionStream(valResultCondition).first, + isFalse, + ); + }); + + test('evaluateConditionStream treats unknown functions and invalid maps as ' + 'false', () async { + final JsonMap unknownFunc = { + 'call': 'noSuchFunction', + 'args': {}, + }; + expect(await context.evaluateConditionStream(unknownFunc).first, isFalse); + + final invalidMap = {'invalid': 'structure'}; + expect(await context.evaluateConditionStream(invalidMap).first, isFalse); + }); + test( - 'evaluateConditionStream treats non-null non-bool objects as true', + 'evaluateConditionStream resolves and/or functions with nested paths and function calls', () async { - dataModel.update(DataPath('/str'), 'hello'); - final condition = {'path': '/str'}; - final Stream stream = context.evaluateConditionStream(condition); - expect(await stream.first, isTrue); // 'hello' != null + final contextWithFuncs = DataContext( + dataModel, + DataPath.root, + functions: BasicCatalogItems.asCatalog().functions, + ); + + dataModel.update(DataPath('/no'), false); + dataModel.update(DataPath('/yes'), true); + + final JsonMap andCondition = { + 'call': 'and', + 'args': { + 'values': [ + {'path': '/no'}, + {'path': '/yes'}, + ], + }, + }; + expect( + await contextWithFuncs.evaluateConditionStream(andCondition).first, + isFalse, + ); + + dataModel.update(DataPath('/no'), true); + expect( + await contextWithFuncs.evaluateConditionStream(andCondition).first, + isTrue, + ); + + final JsonMap orCondition = { + 'call': 'or', + 'args': { + 'values': [ + false, + {'path': '/yes'}, + ], + }, + }; + expect( + await contextWithFuncs.evaluateConditionStream(orCondition).first, + isTrue, + ); }, ); + + test('evaluateConditionStream and checksToExpression correctly validate ' + 'check rules (Issue 2853)', () async { + final contextWithFuncs = DataContext( + dataModel, + DataPath.root, + functions: BasicCatalogItems.asCatalog().functions, + ); + + dataModel.update(DataPath('/email'), ''); + final checks = [ + { + 'condition': { + 'call': 'required', + 'args': { + 'value': {'path': '/email'}, + }, + }, + 'message': 'Required.', + }, + ]; + + // Single check condition alone evaluates to false when empty + expect( + await contextWithFuncs + .evaluateConditionStream(checks.first['condition']) + .first, + isFalse, + ); + + // checksToExpression combined expression evaluates to false when empty + expect( + await contextWithFuncs + .evaluateConditionStream(checksToExpression(checks)) + .first, + isFalse, + ); + + // When populated, both evaluate to true + dataModel.update(DataPath('/email'), 'ada@example.com'); + expect( + await contextWithFuncs + .evaluateConditionStream(checks.first['condition']) + .first, + isTrue, + ); + expect( + await contextWithFuncs + .evaluateConditionStream(checksToExpression(checks)) + .first, + isTrue, + ); + }); }); } diff --git a/packages/genui/test/validation_integration_test.dart b/packages/genui/test/validation_integration_test.dart new file mode 100644 index 000000000..2eddddd12 --- /dev/null +++ b/packages/genui/test/validation_integration_test.dart @@ -0,0 +1,285 @@ +// Copyright 2025 The Flutter Authors. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:genui/genui.dart'; + +import 'test_infra/message_builders.dart'; + +void main() { + group('Validation Integration Tests (reproducing issue 2853)', () { + testWidgets( + 'full form with CheckBox, Slider, ChoicePicker, TextField and Button ' + 'validates rules, displays error messages, and updates Button state', + (WidgetTester tester) async { + final surfaceController = SurfaceController( + catalogs: [BasicCatalogItems.asCatalog()], + ); + addTearDown(surfaceController.dispose); + const surfaceId = 'validationFormSurface'; + + // Initial invalid data model state: + // /email is empty string + // /termsAccepted is false + // /rating is 1.0 (fails minimum of 3.0) + // /plan is empty string + surfaceController.handleMessage( + updateDataModel( + surfaceId: surfaceId, + path: DataPath.root, + value: { + 'email': '', + 'termsAccepted': false, + 'rating': 1.0, + 'plan': '', + }, + ), + ); + + final List components = [ + component( + id: 'root', + type: 'Column', + properties: { + 'children': [ + 'emailField', + 'termsCheckBox', + 'ratingSlider', + 'planPicker', + 'submitButton', + ], + }, + ), + component( + id: 'emailField', + type: 'TextField', + properties: { + 'label': 'Email Address', + 'value': {'path': '/email'}, + 'checks': [ + { + 'message': 'Email is required.', + 'condition': { + 'call': 'required', + 'args': { + 'value': {'path': '/email'}, + }, + }, + }, + ], + }, + ), + component( + id: 'termsCheckBox', + type: 'CheckBox', + properties: { + 'label': 'Accept Terms', + 'value': {'path': '/termsAccepted'}, + 'checks': [ + { + 'message': 'You must accept the terms.', + 'condition': {'path': '/termsAccepted'}, + }, + ], + }, + ), + component( + id: 'ratingSlider', + type: 'Slider', + properties: { + 'label': 'Satisfaction Rating', + 'value': {'path': '/rating'}, + 'min': 0.0, + 'max': 5.0, + 'checks': [ + { + 'message': 'Rating must be at least 3.', + 'condition': { + 'call': 'numeric', + 'args': { + 'value': {'path': '/rating'}, + 'min': 3.0, + }, + }, + }, + ], + }, + ), + component( + id: 'planPicker', + type: 'ChoicePicker', + properties: { + 'label': 'Select Plan', + 'variant': 'mutuallyExclusive', + 'options': [ + {'label': 'Free', 'value': 'free'}, + {'label': 'Pro', 'value': 'pro'}, + ], + 'value': {'path': '/plan'}, + 'checks': [ + { + 'message': 'A plan must be selected.', + 'condition': { + 'call': 'required', + 'args': { + 'value': {'path': '/plan'}, + }, + }, + }, + ], + }, + ), + component( + id: 'submitButton', + type: 'Button', + properties: { + 'child': 'submitText', + 'checks': [ + { + 'message': 'All form requirements must be satisfied.', + 'condition': { + 'call': 'and', + 'args': { + 'values': [ + { + 'call': 'required', + 'args': { + 'value': {'path': '/email'}, + }, + }, + {'path': '/termsAccepted'}, + { + 'call': 'numeric', + 'args': { + 'value': {'path': '/rating'}, + 'min': 3.0, + }, + }, + { + 'call': 'required', + 'args': { + 'value': {'path': '/plan'}, + }, + }, + ], + }, + }, + }, + ], + 'action': { + 'event': {'name': 'submitForm'}, + }, + }, + ), + component( + id: 'submitText', + type: 'Text', + properties: {'text': 'Submit Registration'}, + ), + ]; + + surfaceController.handleMessage( + updateComponents(surfaceId: surfaceId, components: components), + ); + surfaceController.handleMessage( + createSurface(surfaceId: surfaceId, catalogId: basicCatalogId), + ); + + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: SingleChildScrollView( + child: Surface( + surfaceContext: surfaceController.contextFor(surfaceId), + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + + // 1. Initial State: All 4 components fail validation and display + // their respective authored messages. + expect(find.text('Email is required.'), findsOneWidget); + expect(find.text('You must accept the terms.'), findsOneWidget); + expect(find.text('Rating must be at least 3.'), findsOneWidget); + expect(find.text('A plan must be selected.'), findsOneWidget); + + // Submit button is disabled because its `and` checks fail. + final ElevatedButton submitButton = tester.widget( + find.widgetWithText(ElevatedButton, 'Submit Registration'), + ); + expect( + submitButton.onPressed, + isNull, + reason: 'Button must be disabled when validation checks fail', + ); + + // 2. Fix Email + surfaceController.handleMessage( + updateDataModel( + surfaceId: surfaceId, + path: DataPath('/email'), + value: 'user@example.com', + ), + ); + await tester.pumpAndSettle(); + expect(find.text('Email is required.'), findsNothing); + // Button still disabled + expect( + tester + .widget( + find.widgetWithText(ElevatedButton, 'Submit Registration'), + ) + .onPressed, + isNull, + ); + + // 3. Fix Terms CheckBox + surfaceController.handleMessage( + updateDataModel( + surfaceId: surfaceId, + path: DataPath('/termsAccepted'), + value: true, + ), + ); + await tester.pumpAndSettle(); + expect(find.text('You must accept the terms.'), findsNothing); + + // 4. Fix Rating Slider + surfaceController.handleMessage( + updateDataModel( + surfaceId: surfaceId, + path: DataPath('/rating'), + value: 4.0, + ), + ); + await tester.pumpAndSettle(); + expect(find.text('Rating must be at least 3.'), findsNothing); + + // 5. Fix Plan ChoicePicker + surfaceController.handleMessage( + updateDataModel( + surfaceId: surfaceId, + path: DataPath('/plan'), + value: 'pro', + ), + ); + await tester.pumpAndSettle(); + expect(find.text('A plan must be selected.'), findsNothing); + + // 6. Now that all checks pass, the Submit button becomes enabled! + final ElevatedButton enabledButton = tester.widget( + find.widgetWithText(ElevatedButton, 'Submit Registration'), + ); + expect( + enabledButton.onPressed, + isNotNull, + reason: 'Button must be enabled when all validation checks pass', + ); + }, + ); + }); +}