text_input_widget.dart 14 KB

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