text_input_widget.dart 14 KB

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