From 793e7096c04c9717d4a536fa581d2bf419539ccf Mon Sep 17 00:00:00 2001 From: Jacob Simionato Date: Tue, 29 Sep 2026 14:38:44 +0930 Subject: [PATCH 1/3] fix: fix validation checks and preserve error messages in basic catalog - Resolve List arguments recursively in DataContext._evaluateStream so that logical functions (`and`, `or`) receive resolved values instead of raw expression maps. - Handle tolerant unwrapping for 'functionCall' in _evaluateStream and remove the invalid 'functionCall' envelope from checksToExpression. - Align _isTruthy and evaluateConditionStream truthiness semantics to avoid treating unresolved expression maps or unknown functions as truthy. - Migrate CheckBox, Slider, and ChoicePicker to ValidationHelper.validateStream so that each check rule is evaluated individually and the authored error message is preserved and displayed when a check fails. - Add comprehensive unit tests in data_model_test.dart and widget tests for CheckBox, Slider, and ChoicePicker validation. Fixes a2ui-project/a2ui#2853 --- .../basic_catalog_widgets/check_box.dart | 16 +-- .../basic_catalog_widgets/choice_picker.dart | 16 +-- .../catalog/basic_catalog_widgets/slider.dart | 16 +-- .../basic_catalog_widgets/widget_helpers.dart | 17 ++- .../lib/src/catalog/basic_functions.dart | 11 +- packages/genui/lib/src/model/data_model.dart | 22 ++- .../catalog/core_widgets/check_box_test.dart | 65 +++++++++ .../core_widgets/choice_picker_test.dart | 76 +++++++++++ .../catalog/core_widgets/slider_test.dart | 63 +++++++++ .../genui/test/model/data_model_test.dart | 127 +++++++++++++++++- 10 files changed, 394 insertions(+), 35 deletions(-) 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 37278473c..c80d271b9 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( @@ -88,7 +88,7 @@ final checkBox = CatalogItem( }, subtitle: isError ? 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 482430eee..3294f2458 100644 --- a/packages/genui/lib/src/catalog/basic_functions.dart +++ b/packages/genui/lib/src/catalog/basic_functions.dart @@ -52,7 +52,16 @@ class BasicFunctions { bool _isTruthy(Object? value) { if (value is bool) return value; if (value == null) return false; - return true; + 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 false; + } + return false; } /// Checks if all values in a list are truthy. diff --git a/packages/genui/lib/src/model/data_model.dart b/packages/genui/lib/src/model/data_model.dart index 982b2bace..a5b5aa6f6 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); @@ -170,7 +180,17 @@ class DataContext implements cf.ExecutionContext { final Stream resultStream = _evaluateStream(condition); return resultStream.map((v) { if (v is bool) return v; - return v != null; + if (v == null) return false; + if (v is String) return v.isNotEmpty; + if (v is num) return v != 0 && !v.isNaN; + if (v is List) return v.isNotEmpty; + if (v is Map) { + if (v.containsKey('valid') && v['valid'] is bool) { + return v['valid'] as bool; + } + return false; + } + return false; }); } } 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 38aea9824..d6c7ad7db 100644 --- a/packages/genui/test/catalog/core_widgets/check_box_test.dart +++ b/packages/genui/test/catalog/core_widgets/check_box_test.dart @@ -64,4 +64,69 @@ void main() { isFalse, ); }); + + 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..ff0cdf54c 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,128 @@ 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); + }); + + 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, + ); + }); }); } From d4bc88deeb2faf744864d9e4079a34975c706cee Mon Sep 17 00:00:00 2001 From: Jacob Simionato Date: Tue, 29 Sep 2026 15:04:57 +0930 Subject: [PATCH 2/3] fix: address review feedback and add integration test for issue 2853 - Use direct null check on errorMessage in CheckBox subtitle for type promotion. - Extract truthiness evaluation into shared isTruthy function in data_model.dart. - Add validation_integration_test.dart reproducing issue 2853 across components. --- .../basic_catalog_widgets/check_box.dart | 2 +- .../lib/src/catalog/basic_functions.dart | 23 +- packages/genui/lib/src/model/data_model.dart | 31 +- .../test/validation_integration_test.dart | 285 ++++++++++++++++++ 4 files changed, 307 insertions(+), 34 deletions(-) create mode 100644 packages/genui/test/validation_integration_test.dart 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 c80d271b9..027db9d73 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 @@ -86,7 +86,7 @@ final checkBox = CatalogItem( ); } }, - subtitle: isError + subtitle: errorMessage != null ? Text( errorMessage, style: TextStyle( diff --git a/packages/genui/lib/src/catalog/basic_functions.dart b/packages/genui/lib/src/catalog/basic_functions.dart index 3294f2458..aae5b4c99 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,22 +49,6 @@ class BasicFunctions { ]; } -/// Helper to check for truthiness. -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 false; - } - return false; -} - /// Checks if all values in a list are truthy. class AndFunction extends SynchronousClientFunction { const AndFunction(); @@ -87,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; } @@ -117,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; } @@ -143,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 a5b5aa6f6..f49c26f18 100644 --- a/packages/genui/lib/src/model/data_model.dart +++ b/packages/genui/lib/src/model/data_model.dart @@ -178,21 +178,24 @@ class DataContext implements cf.ExecutionContext { if (condition is bool) return Stream.value(condition); final Stream resultStream = _evaluateStream(condition); - return resultStream.map((v) { - if (v is bool) return v; - if (v == null) return false; - if (v is String) return v.isNotEmpty; - if (v is num) return v != 0 && !v.isNaN; - if (v is List) return v.isNotEmpty; - if (v is Map) { - if (v.containsKey('valid') && v['valid'] is bool) { - return v['valid'] as bool; - } - return false; - } - return false; - }); + 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 false; } + return false; } /// Resolves a context map definition against a [DataContext]. 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', + ); + }, + ); + }); +} From 12db51ac3bada0d8ee0dc48548e5a7010147f200 Mon Sep 17 00:00:00 2001 From: Jacob Simionato Date: Wed, 30 Sep 2026 12:31:40 +0930 Subject: [PATCH 3/3] fix: align data map truthiness, add condition warning, and bump to 0.10.5 - Treat non-empty data model maps as truthy in isTruthy, matching lists and strings. - Add warning logs when function calls miss the 'call' property or condition expressions are invalid maps. - Bump genui to 0.10.5 and add CHANGELOG.md entry to satisfy CI changelog check. --- packages/genui/CHANGELOG.md | 8 +++++ packages/genui/lib/src/model/data_model.dart | 13 +++++++- packages/genui/pubspec.yaml | 2 +- .../genui/test/model/data_model_test.dart | 31 +++++++++++++++++++ 4 files changed, 52 insertions(+), 2 deletions(-) diff --git a/packages/genui/CHANGELOG.md b/packages/genui/CHANGELOG.md index 3013a3a04..9a7b1a9c5 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/model/data_model.dart b/packages/genui/lib/src/model/data_model.dart index f49c26f18..7034de67f 100644 --- a/packages/genui/lib/src/model/data_model.dart +++ b/packages/genui/lib/src/model/data_model.dart @@ -133,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); } @@ -177,6 +180,14 @@ 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(isTruthy); } @@ -193,7 +204,7 @@ bool isTruthy(Object? value) { if (value.containsKey('valid') && value['valid'] is bool) { return value['valid'] as bool; } - return false; + return value.isNotEmpty; } return false; } 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/model/data_model_test.dart b/packages/genui/test/model/data_model_test.dart index ff0cdf54c..799341bd1 100644 --- a/packages/genui/test/model/data_model_test.dart +++ b/packages/genui/test/model/data_model_test.dart @@ -412,6 +412,37 @@ void main() { 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 '