text_input_widget.dart 13 KB

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