text_input_widget.dart 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. import 'package:flutter/material.dart';
  2. import 'package:flutter/services.dart';
  3. import 'package:photos/models/execution_states.dart';
  4. import 'package:photos/models/typedefs.dart';
  5. import 'package:photos/theme/ente_theme.dart';
  6. import 'package:photos/ui/common/loading_widget.dart';
  7. import 'package:photos/utils/debouncer.dart';
  8. import 'package:photos/utils/separators_util.dart';
  9. class TextInputWidget extends StatefulWidget {
  10. final String? label;
  11. final String? message;
  12. final String? hintText;
  13. final IconData? prefixIcon;
  14. final String? initialValue;
  15. final Alignment? alignMessage;
  16. final bool? autoFocus;
  17. final int? maxLength;
  18. ///TextInputWidget will listen to this notifier and executes onSubmit when
  19. ///notified.
  20. final ValueNotifier? submitNotifier;
  21. final bool alwaysShowSuccessState;
  22. final bool showOnlyLoadingState;
  23. final FutureVoidCallbackParamStr onSubmit;
  24. final bool popNavAfterSubmission;
  25. final bool shouldSurfaceExecutionStates;
  26. final TextCapitalization? textCapitalization;
  27. final bool isPasswordInput;
  28. const TextInputWidget({
  29. required this.onSubmit,
  30. this.label,
  31. this.message,
  32. this.hintText,
  33. this.prefixIcon,
  34. this.initialValue,
  35. this.alignMessage,
  36. this.autoFocus,
  37. this.maxLength,
  38. this.submitNotifier,
  39. this.alwaysShowSuccessState = false,
  40. this.showOnlyLoadingState = false,
  41. this.popNavAfterSubmission = false,
  42. this.shouldSurfaceExecutionStates = true,
  43. this.textCapitalization = TextCapitalization.none,
  44. this.isPasswordInput = false,
  45. super.key,
  46. });
  47. @override
  48. State<TextInputWidget> createState() => _TextInputWidgetState();
  49. }
  50. class _TextInputWidgetState extends State<TextInputWidget> {
  51. ExecutionState executionState = ExecutionState.idle;
  52. final _textController = TextEditingController();
  53. final _debouncer = Debouncer(const Duration(milliseconds: 300));
  54. late final ValueNotifier<bool> _obscureTextNotifier;
  55. ///This is to pass if the TextInputWidget is in a dialog and an error is
  56. ///thrown in executing onSubmit by passing it as arg in Navigator.pop()
  57. Exception? _exception;
  58. @override
  59. void initState() {
  60. widget.submitNotifier?.addListener(_onSubmit);
  61. if (widget.initialValue != null) {
  62. _textController.value = TextEditingValue(
  63. text: widget.initialValue!,
  64. selection: TextSelection.collapsed(offset: widget.initialValue!.length),
  65. );
  66. }
  67. _obscureTextNotifier = ValueNotifier(widget.isPasswordInput);
  68. _obscureTextNotifier.addListener(_safeRefresh);
  69. super.initState();
  70. }
  71. @override
  72. void dispose() {
  73. widget.submitNotifier?.removeListener(_onSubmit);
  74. _obscureTextNotifier.dispose();
  75. _textController.dispose();
  76. super.dispose();
  77. }
  78. @override
  79. Widget build(BuildContext context) {
  80. if (executionState == ExecutionState.successful) {
  81. Future.delayed(Duration(seconds: widget.popNavAfterSubmission ? 1 : 2),
  82. () {
  83. setState(() {
  84. executionState = ExecutionState.idle;
  85. });
  86. });
  87. }
  88. final colorScheme = getEnteColorScheme(context);
  89. final textTheme = getEnteTextTheme(context);
  90. var textInputChildren = <Widget>[];
  91. if (widget.label != null) {
  92. textInputChildren.add(Text(widget.label!));
  93. }
  94. textInputChildren.add(
  95. ClipRRect(
  96. borderRadius: const BorderRadius.all(Radius.circular(8)),
  97. child: Material(
  98. child: TextFormField(
  99. textCapitalization: widget.textCapitalization!,
  100. autofocus: widget.autoFocus ?? false,
  101. controller: _textController,
  102. inputFormatters: widget.maxLength != null
  103. ? [LengthLimitingTextInputFormatter(50)]
  104. : null,
  105. obscureText: _obscureTextNotifier.value,
  106. decoration: InputDecoration(
  107. hintText: widget.hintText,
  108. hintStyle: textTheme.body.copyWith(color: colorScheme.textMuted),
  109. filled: true,
  110. fillColor: colorScheme.fillFaint,
  111. contentPadding: const EdgeInsets.fromLTRB(
  112. 12,
  113. 12,
  114. 0,
  115. 12,
  116. ),
  117. border: const UnderlineInputBorder(
  118. borderSide: BorderSide.none,
  119. ),
  120. focusedBorder: OutlineInputBorder(
  121. borderSide: BorderSide(color: colorScheme.strokeMuted),
  122. borderRadius: BorderRadius.circular(8),
  123. ),
  124. suffixIcon: Padding(
  125. padding: const EdgeInsets.symmetric(horizontal: 12),
  126. child: AnimatedSwitcher(
  127. duration: const Duration(milliseconds: 175),
  128. switchInCurve: Curves.easeInExpo,
  129. switchOutCurve: Curves.easeOutExpo,
  130. child: SuffixIconWidget(
  131. key: ValueKey(executionState),
  132. executionState: executionState,
  133. shouldSurfaceExecutionStates:
  134. widget.shouldSurfaceExecutionStates,
  135. obscureTextNotifier: _obscureTextNotifier,
  136. ),
  137. ),
  138. ),
  139. prefixIconConstraints: const BoxConstraints(
  140. maxHeight: 44,
  141. maxWidth: 44,
  142. minHeight: 44,
  143. minWidth: 44,
  144. ),
  145. suffixIconConstraints: const BoxConstraints(
  146. maxHeight: 24,
  147. maxWidth: 48,
  148. minHeight: 24,
  149. minWidth: 48,
  150. ),
  151. prefixIcon: widget.prefixIcon != null
  152. ? Icon(
  153. widget.prefixIcon,
  154. color: colorScheme.strokeMuted,
  155. )
  156. : null,
  157. ),
  158. onEditingComplete: () {
  159. _onSubmit();
  160. },
  161. ),
  162. ),
  163. ),
  164. );
  165. if (widget.message != null) {
  166. textInputChildren.add(
  167. Padding(
  168. padding: const EdgeInsets.symmetric(horizontal: 8),
  169. child: Align(
  170. alignment: widget.alignMessage ?? Alignment.centerLeft,
  171. child: Text(
  172. widget.message!,
  173. style: textTheme.small.copyWith(color: colorScheme.textMuted),
  174. ),
  175. ),
  176. ),
  177. );
  178. }
  179. textInputChildren =
  180. addSeparators(textInputChildren, const SizedBox(height: 4));
  181. return Column(
  182. mainAxisSize: MainAxisSize.min,
  183. crossAxisAlignment: CrossAxisAlignment.start,
  184. children: textInputChildren,
  185. );
  186. }
  187. void _safeRefresh() {
  188. if (mounted) {
  189. setState(() {});
  190. }
  191. }
  192. void _onSubmit() async {
  193. _debouncer.run(
  194. () => Future(() {
  195. setState(() {
  196. executionState = ExecutionState.inProgress;
  197. });
  198. }),
  199. );
  200. try {
  201. await widget.onSubmit.call(_textController.text);
  202. } catch (e) {
  203. executionState = ExecutionState.error;
  204. _debouncer.cancelDebounce();
  205. _exception = e as Exception;
  206. if (!widget.popNavAfterSubmission) {
  207. rethrow;
  208. }
  209. }
  210. widget.alwaysShowSuccessState && _debouncer.isActive()
  211. ? executionState = ExecutionState.successful
  212. : null;
  213. _debouncer.cancelDebounce();
  214. if (executionState == ExecutionState.successful) {
  215. setState(() {});
  216. }
  217. // when the time taken by widget.onSubmit is approximately equal to the debounce
  218. // time, the callback is getting executed when/after the if condition
  219. // below is executing/executed which results in execution state stuck at
  220. // idle state. This Future is for delaying the execution of the if
  221. // condition so that the calback in the debouncer finishes execution before.
  222. await Future.delayed(const Duration(milliseconds: 5));
  223. if (executionState == ExecutionState.inProgress ||
  224. executionState == ExecutionState.error) {
  225. if (executionState == ExecutionState.inProgress) {
  226. if (mounted) {
  227. if (widget.showOnlyLoadingState) {
  228. setState(() {
  229. executionState = ExecutionState.idle;
  230. });
  231. _popNavigatorStack(context);
  232. } else {
  233. setState(() {
  234. executionState = ExecutionState.successful;
  235. Future.delayed(
  236. Duration(
  237. seconds: widget.shouldSurfaceExecutionStates
  238. ? (widget.popNavAfterSubmission ? 1 : 2)
  239. : 0,
  240. ), () {
  241. widget.popNavAfterSubmission
  242. ? _popNavigatorStack(context)
  243. : null;
  244. if (mounted) {
  245. setState(() {
  246. executionState = ExecutionState.idle;
  247. });
  248. }
  249. });
  250. });
  251. }
  252. }
  253. }
  254. if (executionState == ExecutionState.error) {
  255. setState(() {
  256. executionState = ExecutionState.idle;
  257. widget.popNavAfterSubmission
  258. ? Future.delayed(
  259. const Duration(seconds: 0),
  260. () => _popNavigatorStack(context, e: _exception),
  261. )
  262. : null;
  263. });
  264. }
  265. } else {
  266. if (widget.popNavAfterSubmission) {
  267. Future.delayed(
  268. Duration(seconds: widget.alwaysShowSuccessState ? 1 : 0),
  269. () => _popNavigatorStack(context),
  270. );
  271. }
  272. }
  273. }
  274. void _popNavigatorStack(BuildContext context, {Exception? e}) {
  275. Navigator.of(context).canPop() ? Navigator.of(context).pop(e) : null;
  276. }
  277. }
  278. //todo: Add clear and custom icon for suffic icon
  279. class SuffixIconWidget extends StatelessWidget {
  280. final ExecutionState executionState;
  281. final bool shouldSurfaceExecutionStates;
  282. final ValueNotifier? obscureTextNotifier;
  283. const SuffixIconWidget({
  284. required this.executionState,
  285. required this.shouldSurfaceExecutionStates,
  286. this.obscureTextNotifier,
  287. super.key,
  288. });
  289. @override
  290. Widget build(BuildContext context) {
  291. final Widget trailingWidget;
  292. final colorScheme = getEnteColorScheme(context);
  293. if (executionState == ExecutionState.idle ||
  294. !shouldSurfaceExecutionStates) {
  295. if (obscureTextNotifier != null) {
  296. trailingWidget = GestureDetector(
  297. onTap: () {
  298. obscureTextNotifier!.value = !obscureTextNotifier!.value;
  299. },
  300. child: Icon(
  301. obscureTextNotifier!.value
  302. ? Icons.visibility_off_outlined
  303. : Icons.visibility,
  304. color: obscureTextNotifier!.value ? colorScheme.strokeMuted : null,
  305. ),
  306. );
  307. } else {
  308. trailingWidget = const SizedBox.shrink();
  309. }
  310. } else if (executionState == ExecutionState.inProgress) {
  311. trailingWidget = EnteLoadingWidget(
  312. color: colorScheme.strokeMuted,
  313. );
  314. } else if (executionState == ExecutionState.successful) {
  315. trailingWidget = Icon(
  316. Icons.check_outlined,
  317. size: 22,
  318. color: colorScheme.primary500,
  319. );
  320. } else {
  321. trailingWidget = const SizedBox.shrink();
  322. }
  323. return trailingWidget;
  324. }
  325. }