text_input_widget.dart 12 KB

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