import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import '../../../core/api_gateway.dart'; import 'chat_card_styles.dart'; import 'chat_question_card_model.dart'; import 'chat_question_markdown.dart'; import 'chat_composer_bar.dart' show chatEnterSends; import 'chat_no_reveal.dart'; import 'chat_question_option_controls.dart'; /// A free-text input is part of a field when the form allows an answer outside /// its option list, or when the field has no options at all. bool chatQuestionFieldNeedsInput(JsonMap field) => field['custom'] == true || chatQuestionOptions(field).isEmpty; /// The editable controls for one form. [onChanged] receives the protocol value /// (`false`/`0` preserved), or null when the input was cleared. List chatQuestionFieldWidgets({ required BuildContext context, required List fields, required Map answers, required Map controllers, required void Function(String key, Object? value) onChanged, VoidCallback? onSubmit, }) { final widgets = []; for (final field in fields) { if (!chatFormFieldVisible(field, answers)) continue; final key = '${field['key'] ?? ''}'.trim(); if (key.isEmpty) continue; widgets.add( _field( context: context, field: field, keyName: key, answers: answers, controllers: controllers, onChanged: onChanged, onSubmit: onSubmit, ), ); } return widgets; } Widget _field({ required BuildContext context, required JsonMap field, required String keyName, required Map answers, required Map controllers, required void Function(String key, Object? value) onChanged, VoidCallback? onSubmit, }) { final title = '${field['title'] ?? ''}'.trim(); final description = '${field['description'] ?? ''}'.trim(); final label = title.isNotEmpty ? title : (description.isNotEmpty ? description : keyName); return Padding( padding: const EdgeInsets.only(top: 12), child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, mainAxisSize: MainAxisSize.min, children: [ ChatQuestionMarkdown(label, style: chatCardLabelStyle(context)), if (description.isNotEmpty && description != title) ChatQuestionMarkdown( description, style: chatCardSecondaryStyle(context), ), if ('${field['type'] ?? ''}' == 'external') _external(context, field) else if ('${field['type'] ?? ''}' == 'boolean') chatQuestionBooleanField( context: context, field: field, keyName: keyName, answers: answers, onChanged: onChanged, ) else ...[ chatQuestionOptionsField( context: context, field: field, keyName: keyName, answers: answers, onChanged: onChanged, ), if (chatQuestionFieldNeedsInput(field)) _input( context: context, field: field, label: label, keyName: keyName, controller: controllers[keyName]!, hasOptions: chatQuestionOptions(field).isNotEmpty, onSubmit: onSubmit, onChanged: (value) => onChanged( keyName, chatQuestionTextValue(field, value, answers), ), ), ], ], ), ); } Widget _input({ required BuildContext context, required JsonMap field, required String label, required String keyName, required TextEditingController controller, required bool hasOptions, required ValueChanged onChanged, VoidCallback? onSubmit, }) { final placeholder = '${field['placeholder'] ?? ''}'.trim().isNotEmpty ? '${field['placeholder']}'.trim() : (hasOptions ? 'Type another answer' : 'Your answer'); final secret = field['secret'] == true; final type = '${field['type'] ?? ''}'; final format = '${field['format'] ?? ''}'; final keyboard = type == 'number' || type == 'integer' ? TextInputType.number : format == 'email' ? TextInputType.emailAddress : format == 'uri' ? TextInputType.url : format == 'date' ? TextInputType.datetime : TextInputType.text; // The visual label sits above the input; the same words must also reach the // input's own semantics node, as the web's `aria-label` does. // A free-text answer behaves like the chat composer: it grows to a few // lines, Enter sends (on a desktop or web keyboard) and Shift+Enter breaks // the line. A secret or typed (number, email, ...) answer stays one line. final multiline = keyboard == TextInputType.text && !secret; final input = TextField( key: ValueKey('chat-question-input-$keyName'), controller: controller, obscureText: secret, keyboardType: multiline ? TextInputType.multiline : keyboard, minLines: 1, maxLines: multiline ? 6 : 1, textInputAction: multiline && !chatEnterSends() ? TextInputAction.newline : TextInputAction.done, decoration: InputDecoration(hintText: placeholder), onChanged: onChanged, onSubmitted: onSubmit == null ? null : (_) => onSubmit(), ); return Semantics( label: label, child: ChatNoReveal( child: Focus( canRequestFocus: false, skipTraversal: true, onKeyEvent: (_, event) => _enterKey(event, controller, multiline, onChanged, onSubmit), child: input, ), ), ); } Widget _external(BuildContext context, JsonMap field) { final raw = '${field['url'] ?? ''}'.trim(); if (!chatExternalUrlIsSafe(raw)) { return Text( 'This form has an unsupported external URL.', style: chatCardBodyStyle( context, )?.copyWith(color: chatCardErrorColor(context)), ); } return SelectableText(raw); } /// Enter sends the answer and Shift+Enter breaks the line, as in the chat /// composer. An open IME candidate keeps its Enter, and a phone keyboard's /// Return stays the field's own newline. KeyEventResult _enterKey( KeyEvent event, TextEditingController controller, bool multiline, ValueChanged onChanged, VoidCallback? onSubmit, ) { final key = event.logicalKey; if (key != LogicalKeyboardKey.enter && key != LogicalKeyboardKey.numpadEnter) { return KeyEventResult.ignored; } final value = controller.value; if (value.composing.isValid && !value.composing.isCollapsed) { return KeyEventResult.ignored; } if (!chatEnterSends()) return KeyEventResult.ignored; final keyboard = HardwareKeyboard.instance; if (keyboard.isShiftPressed) { if (!multiline) return KeyEventResult.handled; if (event is KeyDownEvent || event is KeyRepeatEvent) { final selection = value.selection; final start = selection.isValid ? selection.start : value.text.length; final end = selection.isValid ? selection.end : start; final text = value.text.replaceRange(start, end, '\n'); controller.value = TextEditingValue( text: text, selection: TextSelection.collapsed(offset: start + 1), ); onChanged(text); } return KeyEventResult.handled; } if (keyboard.isAltPressed || keyboard.isControlPressed || keyboard.isMetaPressed) { return KeyEventResult.ignored; } // A held key must not send twice. if (event is KeyDownEvent) onSubmit?.call(); return KeyEventResult.handled; }