stack_wallet/lib/pages/send_view/frost_ms/recipient.dart

456 lines
16 KiB
Dart
Raw Normal View History

2024-01-24 00:33:40 +00:00
import 'package:decimal/decimal.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
2024-05-27 23:56:22 +00:00
import '../../../providers/global/locale_provider.dart';
import '../../../themes/stack_colors.dart';
import '../../../utilities/address_utils.dart';
import '../../../utilities/amount/amount.dart';
import '../../../utilities/amount/amount_formatter.dart';
import '../../../utilities/amount/amount_input_formatter.dart';
import '../../../utilities/amount/amount_unit.dart';
import '../../../utilities/barcode_scanner_interface.dart';
import '../../../utilities/clipboard_interface.dart';
import '../../../utilities/constants.dart';
import '../../../utilities/logger.dart';
import '../../../utilities/text_styles.dart';
import '../../../utilities/util.dart';
import '../../../wallets/crypto_currency/crypto_currency.dart';
import '../../../widgets/custom_buttons/blue_text_button.dart';
import '../../../widgets/icon_widgets/clipboard_icon.dart';
import '../../../widgets/icon_widgets/qrcode_icon.dart';
import '../../../widgets/icon_widgets/x_icon.dart';
import '../../../widgets/rounded_container.dart';
import '../../../widgets/stack_text_field.dart';
import '../../../widgets/textfield_icon_button.dart';
2024-01-24 00:33:40 +00:00
//TODO: move the following two providers elsewhere
final pClipboard =
Provider<ClipboardInterface>((ref) => const ClipboardWrapper());
final pBarcodeScanner =
Provider<BarcodeScannerInterface>((ref) => const BarcodeScannerWrapper());
// final _pPrice = Provider.family<Decimal, Coin>((ref, coin) {
// return ref.watch(
// priceAnd24hChangeNotifierProvider
// .select((value) => value.getPrice(coin).item1),
// );
// });
final pRecipient =
StateProvider.family<({String address, Amount? amount})?, int>(
2024-05-27 23:56:22 +00:00
(ref, index) => null,
);
2024-01-24 00:33:40 +00:00
class Recipient extends ConsumerStatefulWidget {
const Recipient({
super.key,
required this.index,
2024-05-01 22:05:35 +00:00
required this.displayNumber,
2024-01-24 00:33:40 +00:00
required this.coin,
this.remove,
this.onChanged,
2024-05-01 22:05:35 +00:00
required this.addAnotherRecipientTapped,
required this.sendAllTapped,
2024-01-24 00:33:40 +00:00
});
final int index;
2024-05-01 22:05:35 +00:00
final int displayNumber;
2024-05-15 21:20:45 +00:00
final CryptoCurrency coin;
2024-01-24 00:33:40 +00:00
final VoidCallback? remove;
final VoidCallback? onChanged;
2024-05-01 22:05:35 +00:00
final VoidCallback addAnotherRecipientTapped;
final String Function() sendAllTapped;
2024-01-24 00:33:40 +00:00
@override
ConsumerState<Recipient> createState() => _RecipientState();
}
class _RecipientState extends ConsumerState<Recipient> {
late final TextEditingController addressController, amountController;
late final FocusNode addressFocusNode, amountFocusNode;
bool _addressIsEmpty = true;
2024-05-01 22:05:35 +00:00
final bool _cryptoAmountChangeLock = false;
bool get isSingle => widget.remove == null;
2024-01-24 00:33:40 +00:00
void _updateRecipientData() {
final address = addressController.text;
final amount =
ref.read(pAmountFormatter(widget.coin)).tryParse(amountController.text);
ref.read(pRecipient(widget.index).notifier).state = (
address: address,
amount: amount,
);
widget.onChanged?.call();
}
void _cryptoAmountChanged() async {
if (!_cryptoAmountChangeLock) {
Amount? cryptoAmount = ref.read(pAmountFormatter(widget.coin)).tryParse(
amountController.text,
);
if (cryptoAmount != null) {
if (ref.read(pRecipient(widget.index))?.amount != null &&
ref.read(pRecipient(widget.index))?.amount == cryptoAmount) {
return;
}
// final price = ref.read(_pPrice(widget.coin));
//
// if (price > Decimal.zero) {
// baseController.text = (cryptoAmount.decimal * price)
// .toAmount(
// fractionDigits: 2,
// )
// .fiatString(
// locale: ref.read(localeServiceChangeNotifierProvider).locale,
// );
// }
} else {
cryptoAmount = null;
// baseController.text = "";
}
_updateRecipientData();
}
}
@override
void initState() {
addressController = TextEditingController();
amountController = TextEditingController();
// baseController = TextEditingController();
2024-05-01 22:05:35 +00:00
final amount = ref.read(pRecipient(widget.index))?.amount;
if (amount != null) {
amountController.text = ref
.read(pAmountFormatter(widget.coin))
.format(amount, withUnitName: false);
}
addressController.text = ref.read(pRecipient(widget.index))?.address ?? "";
_addressIsEmpty = addressController.text.isEmpty;
2024-01-24 00:33:40 +00:00
addressFocusNode = FocusNode();
amountFocusNode = FocusNode();
// baseFocusNode = FocusNode();
amountController.addListener(_cryptoAmountChanged);
super.initState();
}
@override
void dispose() {
amountController.removeListener(_cryptoAmountChanged);
addressController.dispose();
amountController.dispose();
// baseController.dispose();
addressFocusNode.dispose();
amountFocusNode.dispose();
// baseFocusNode.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final String locale = ref.watch(
localeServiceChangeNotifierProvider.select(
(value) => value.locale,
),
);
2024-05-01 22:05:35 +00:00
return RoundedContainer(
color: Colors.transparent,
2024-01-26 01:04:07 +00:00
padding: const EdgeInsets.all(0),
2024-01-24 00:33:40 +00:00
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
2024-05-01 22:05:35 +00:00
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
isSingle ? "Send to" : "Recipient ${widget.displayNumber}",
style: STextStyles.smallMed12(context),
textAlign: TextAlign.left,
),
CustomTextButton(
text: isSingle ? "Add another recipient" : "Remove",
onTap:
isSingle ? widget.addAnotherRecipientTapped : widget.remove,
),
],
),
const SizedBox(
height: 8,
),
2024-01-24 00:33:40 +00:00
ClipRRect(
borderRadius: BorderRadius.circular(
Constants.size.circularBorderRadius,
),
child: TextField(
key: const Key("sendViewAddressFieldKey"),
controller: addressController,
readOnly: false,
autocorrect: false,
enableSuggestions: false,
focusNode: addressFocusNode,
style: STextStyles.field(context),
onChanged: (_) {
2024-05-01 22:30:37 +00:00
_updateRecipientData();
2024-01-24 00:33:40 +00:00
setState(() {
_addressIsEmpty = addressController.text.isEmpty;
});
},
decoration: standardInputDecoration(
"Enter ${widget.coin.ticker} address",
addressFocusNode,
context,
).copyWith(
contentPadding: const EdgeInsets.only(
left: 16,
top: 6,
bottom: 8,
right: 5,
),
suffixIcon: Padding(
padding: _addressIsEmpty
? const EdgeInsets.only(right: 8)
: const EdgeInsets.only(right: 0),
child: UnconstrainedBox(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
!_addressIsEmpty
? TextFieldIconButton(
semanticsLabel:
"Clear Button. Clears The Address Field Input.",
key: const Key(
2024-05-27 23:56:22 +00:00
"sendViewClearAddressFieldButtonKey",
),
2024-01-24 00:33:40 +00:00
onTap: () {
addressController.text = "";
setState(() {
_addressIsEmpty = true;
});
_updateRecipientData();
},
child: const XIcon(),
)
: TextFieldIconButton(
semanticsLabel:
"Paste Button. Pastes From Clipboard To Address Field Input.",
key: const Key(
2024-05-27 23:56:22 +00:00
"sendViewPasteAddressFieldButtonKey",
),
2024-01-24 00:33:40 +00:00
onTap: () async {
final ClipboardData? data = await ref
.read(pClipboard)
.getData(Clipboard.kTextPlain);
if (data?.text != null &&
data!.text!.isNotEmpty) {
String content = data.text!.trim();
if (content.contains("\n")) {
content = content.substring(
2024-05-27 23:56:22 +00:00
0,
content.indexOf("\n"),
);
2024-01-24 00:33:40 +00:00
}
addressController.text = content.trim();
setState(() {
_addressIsEmpty =
addressController.text.isEmpty;
});
_updateRecipientData();
}
},
child: _addressIsEmpty
? const ClipboardIcon()
: const XIcon(),
),
if (_addressIsEmpty)
TextFieldIconButton(
semanticsLabel: "Scan QR Button. "
"Opens Camera For Scanning QR Code.",
key: const Key(
"sendViewScanQrButtonKey",
),
onTap: () async {
try {
if (FocusScope.of(context).hasFocus) {
FocusScope.of(context).unfocus();
await Future<void>.delayed(
const Duration(
milliseconds: 75,
),
);
}
final qrResult =
await ref.read(pBarcodeScanner).scan();
Logging.instance.log(
"qrResult content: ${qrResult.rawContent}",
level: LogLevel.Info,
);
/// TODO: deal with address utils
final results =
AddressUtils.parseUri(qrResult.rawContent);
Logging.instance.log(
"qrResult parsed: $results",
level: LogLevel.Info,
);
if (results.isNotEmpty &&
results["scheme"] ==
widget.coin.uriScheme) {
// auto fill address
addressController.text =
(results["address"] ?? "").trim();
// autofill amount field
if (results["amount"] != null) {
final Amount amount =
Decimal.parse(results["amount"]!)
.toAmount(
2024-05-15 21:20:45 +00:00
fractionDigits:
widget.coin.fractionDigits,
2024-01-24 00:33:40 +00:00
);
amountController.text = ref
.read(pAmountFormatter(widget.coin))
.format(
amount,
withUnitName: false,
);
}
} else {
addressController.text =
qrResult.rawContent.trim();
}
setState(() {
_addressIsEmpty =
addressController.text.isEmpty;
});
_updateRecipientData();
} on PlatformException catch (e, s) {
Logging.instance.log(
"Failed to get camera permissions while "
"trying to scan qr code in SendView: $e\n$s",
level: LogLevel.Warning,
);
}
},
child: const QrCodeIcon(),
),
],
),
),
),
),
),
),
2024-05-01 22:05:35 +00:00
SizedBox(
height: isSingle ? 12 : 8,
2024-01-24 00:33:40 +00:00
),
2024-05-01 22:05:35 +00:00
if (isSingle)
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
"Amount",
style: STextStyles.smallMed12(context),
textAlign: TextAlign.left,
),
2024-05-02 17:06:42 +00:00
// disable send all since the frost tx creation logic isn't there (yet?)
const Spacer(),
// CustomTextButton(
// text: "Send all ${widget.coin.ticker}",
// onTap: () {
// amountController.text = widget.sendAllTapped();
// _cryptoAmountChanged();
// },
// ),
2024-05-01 22:05:35 +00:00
],
),
if (isSingle)
const SizedBox(
height: 8,
),
2024-01-24 00:33:40 +00:00
TextField(
autocorrect: false,
enableSuggestions: false,
style: STextStyles.smallMed14(context).copyWith(
color: Theme.of(context).extension<StackColors>()!.textDark,
),
key: const Key("amountInputFieldCryptoTextFieldKey"),
controller: amountController,
focusNode: amountFocusNode,
2024-05-01 22:30:37 +00:00
onChanged: (_) {
_updateRecipientData();
},
2024-01-24 00:33:40 +00:00
keyboardType: Util.isDesktop
? null
: const TextInputType.numberWithOptions(
signed: false,
decimal: true,
),
textAlign: TextAlign.right,
inputFormatters: [
AmountInputFormatter(
2024-05-15 21:20:45 +00:00
decimals: widget.coin.fractionDigits,
2024-01-24 00:33:40 +00:00
unit: ref.watch(pAmountUnit(widget.coin)),
locale: locale,
),
],
decoration: InputDecoration(
contentPadding: const EdgeInsets.only(
top: 12,
right: 12,
),
hintText: "0",
hintStyle: STextStyles.fieldLabel(context).copyWith(
fontSize: 14,
),
prefixIcon: FittedBox(
fit: BoxFit.scaleDown,
child: Padding(
padding: const EdgeInsets.all(12),
child: Text(
ref
.watch(pAmountUnit(widget.coin))
.unitForCoin(widget.coin),
style: STextStyles.smallMed14(context).copyWith(
2024-05-27 23:56:22 +00:00
color: Theme.of(context)
.extension<StackColors>()!
.accentColorDark,
),
2024-01-24 00:33:40 +00:00
),
),
),
),
),
],
),
);
}
}