import 'package:flutter/cupertino.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'device_code.dart'; import 'secret.dart'; /// Root widget. Picks Cupertino on iOS/macOS and Material 3 elsewhere, based /// on [platform] when given, otherwise on [defaultTargetPlatform]. class DeviceCodeApp extends StatelessWidget { const DeviceCodeApp({ super.key, this.platform, this.initialDate, this.initialMac, }); /// Forces a platform look; defaults to the running platform. final TargetPlatform? platform; /// Date pre-selected on launch; defaults to today (device local time). final DateTime? initialDate; /// MAC pre-filled on launch (used by previews/tests). final String? initialMac; @override Widget build(BuildContext context) { final effective = platform ?? defaultTargetPlatform; final cupertino = effective == TargetPlatform.iOS || effective == TargetPlatform.macOS; final home = DeviceCodeScreen( cupertino: cupertino, initialDate: initialDate, initialMac: initialMac, ); if (cupertino) { return CupertinoApp( title: 'Device Code', debugShowCheckedModeBanner: false, theme: const CupertinoThemeData( primaryColor: CupertinoColors.activeBlue, ), home: home, ); } return MaterialApp( title: 'Device Code', debugShowCheckedModeBanner: false, theme: ThemeData( useMaterial3: true, colorSchemeSeed: const Color(0xFF1E6FD9), ), darkTheme: ThemeData( useMaterial3: true, brightness: Brightness.dark, colorSchemeSeed: const Color(0xFF1E6FD9), ), home: home, ); } } /// Reformats the typed text to `xx:xx:xx:xx:xx:xx` while typing. class _MacInputFormatter extends TextInputFormatter { const _MacInputFormatter(); @override TextEditingValue formatEditUpdate( TextEditingValue oldValue, TextEditingValue newValue, ) { final formatted = formatMac(newValue.text); return TextEditingValue( text: formatted, selection: TextSelection.collapsed(offset: formatted.length), ); } } class DeviceCodeScreen extends StatefulWidget { const DeviceCodeScreen({ super.key, required this.cupertino, this.initialDate, this.initialMac, }); /// True to render Cupertino widgets, false for Material 3. final bool cupertino; final DateTime? initialDate; final String? initialMac; @override State createState() => _DeviceCodeScreenState(); } class _DeviceCodeScreenState extends State { static const macKey = Key('mac-field'); static const codeKey = Key('device-code'); static const dateKey = Key('code-date'); static const copyKey = Key('copy-button'); late final TextEditingController _mac; late DateTime _date; bool _copied = false; @override void initState() { super.initState(); _mac = TextEditingController(text: formatMac(widget.initialMac ?? '')); _mac.addListener(() => setState(() => _copied = false)); final now = widget.initialDate ?? DateTime.now(); _date = DateTime(now.year, now.month, now.day); } @override void dispose() { _mac.dispose(); super.dispose(); } bool get _ready => isCompleteMac(_mac.text); String get _dateString => formatDateForCode(_date); String? get _code => _ready ? generateDeviceCode( mac: _mac.text, date: _dateString, secret: deviceCodeSecret, ) : null; bool get _isToday { final n = DateTime.now(); return n.year == _date.year && n.month == _date.month && n.day == _date.day; } static const _months = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', ]; String get _prettyDate => '${_date.day} ${_months[_date.month - 1]} ${_date.year}'; void _setDate(DateTime d) { setState(() { _date = DateTime(d.year, d.month, d.day); _copied = false; }); } Future _copy() async { final code = _code; if (code == null) return; await Clipboard.setData(ClipboardData(text: code)); if (!mounted) return; setState(() => _copied = true); if (!_cupertino) { ScaffoldMessenger.of(context) ..hideCurrentSnackBar() ..showSnackBar(SnackBar(content: Text('Copied $code'))); } } bool get _cupertino => widget.cupertino; @override Widget build(BuildContext context) => _cupertino ? _buildCupertino(context) : _buildMaterial(context); // ---------------------------------------------------------------- Material Future _pickDateMaterial() async { final picked = await showDatePicker( context: context, initialDate: _date, firstDate: DateTime(2000), lastDate: DateTime(2100), helpText: 'Date the code is valid for', ); if (picked != null) _setDate(picked); } Widget _buildMaterial(BuildContext context) { final scheme = Theme.of(context).colorScheme; final text = Theme.of(context).textTheme; final code = _code; return Scaffold( appBar: AppBar(title: const Text('Device Code')), body: SafeArea( child: ListView( padding: const EdgeInsets.all(20), children: [ TextField( key: macKey, controller: _mac, autocorrect: false, enableSuggestions: false, keyboardType: TextInputType.visiblePassword, textCapitalization: TextCapitalization.none, inputFormatters: const [_MacInputFormatter()], style: const TextStyle( fontFeatures: [FontFeature.tabularFigures()], ), decoration: InputDecoration( labelText: 'MAC address', hintText: '74:25:84:c0:02:4a', helperText: _ready ? 'Ready' : '12 hex digits required', border: const OutlineInputBorder(), prefixIcon: const Icon(Icons.router_outlined), suffixIcon: _mac.text.isEmpty ? null : IconButton( tooltip: 'Clear', icon: const Icon(Icons.clear), onPressed: () => _mac.clear(), ), ), ), const SizedBox(height: 16), Card.outlined( child: ListTile( leading: const Icon(Icons.event_outlined), title: const Text('Valid for'), subtitle: Text( key: dateKey, '$_prettyDate · $_dateString${_isToday ? ' (today)' : ''}', ), trailing: const Icon(Icons.edit_calendar_outlined), onTap: _pickDateMaterial, ), ), const SizedBox(height: 24), Card.filled( color: scheme.primaryContainer, child: Padding( padding: const EdgeInsets.symmetric( vertical: 28, horizontal: 20, ), child: Column( children: [ Text( 'DEVICE CODE', style: text.labelLarge?.copyWith( color: scheme.onPrimaryContainer, letterSpacing: 1.5, ), ), const SizedBox(height: 12), SelectableText( key: codeKey, code ?? '••••••••', textAlign: TextAlign.center, style: text.displayMedium?.copyWith( color: scheme.onPrimaryContainer, fontWeight: FontWeight.w600, letterSpacing: 4, fontFeatures: const [FontFeature.tabularFigures()], ), ), const SizedBox(height: 20), FilledButton.icon( key: copyKey, onPressed: code == null ? null : _copy, icon: Icon(_copied ? Icons.check : Icons.copy), label: Text(_copied ? 'Copied' : 'Copy code'), ), ], ), ), ), const SizedBox(height: 16), Text( 'Generated offline on this device. The code changes every day; ' 'pick another date if you need a code for a different day.', style: text.bodySmall?.copyWith(color: scheme.onSurfaceVariant), textAlign: TextAlign.center, ), ], ), ), ); } // --------------------------------------------------------------- Cupertino Future _pickDateCupertino() async { var temp = _date; await showCupertinoModalPopup( context: context, builder: (ctx) => Container( height: 300, color: CupertinoColors.systemBackground.resolveFrom(ctx), child: SafeArea( top: false, child: Column( children: [ Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ CupertinoButton( child: const Text('Cancel'), onPressed: () => Navigator.pop(ctx), ), CupertinoButton( child: const Text('Done'), onPressed: () { _setDate(temp); Navigator.pop(ctx); }, ), ], ), Expanded( child: CupertinoDatePicker( mode: CupertinoDatePickerMode.date, initialDateTime: _date, minimumYear: 2000, maximumYear: 2100, onDateTimeChanged: (d) => temp = d, ), ), ], ), ), ), ); } Widget _buildCupertino(BuildContext context) { final code = _code; final secondary = CupertinoColors.secondaryLabel.resolveFrom(context); return CupertinoPageScaffold( navigationBar: const CupertinoNavigationBar(middle: Text('Device Code')), backgroundColor: CupertinoColors.systemGroupedBackground.resolveFrom( context, ), child: SafeArea( child: ListView( children: [ CupertinoFormSection.insetGrouped( header: const Text('DEVICE'), footer: Text(_ready ? 'Ready' : '12 hex digits required'), children: [ CupertinoTextFormFieldRow( key: macKey, controller: _mac, prefix: const Text('MAC'), placeholder: '74:25:84:c0:02:4a', autocorrect: false, enableSuggestions: false, keyboardType: TextInputType.visiblePassword, textCapitalization: TextCapitalization.none, inputFormatters: const [_MacInputFormatter()], style: const TextStyle( fontFeatures: [FontFeature.tabularFigures()], ), textAlign: TextAlign.end, ), CupertinoListTile( leading: const Icon(CupertinoIcons.calendar), title: const Text('Valid for'), additionalInfo: Text( key: dateKey, '$_prettyDate${_isToday ? ' (today)' : ''}', ), trailing: const CupertinoListTileChevron(), onTap: _pickDateCupertino, ), ], ), Padding( padding: const EdgeInsets.fromLTRB(20, 8, 20, 0), child: Container( padding: const EdgeInsets.symmetric( vertical: 28, horizontal: 20, ), decoration: BoxDecoration( color: CupertinoColors.secondarySystemGroupedBackground .resolveFrom(context), borderRadius: BorderRadius.circular(12), ), child: Column( children: [ Text( 'DEVICE CODE · $_dateString', style: TextStyle( color: secondary, fontSize: 13, fontWeight: FontWeight.w600, letterSpacing: 1.2, ), ), const SizedBox(height: 12), SelectableText( key: codeKey, code ?? '••••••••', textAlign: TextAlign.center, style: TextStyle( fontSize: 44, fontWeight: FontWeight.w600, letterSpacing: 4, color: CupertinoColors.label.resolveFrom(context), fontFeatures: const [FontFeature.tabularFigures()], ), ), const SizedBox(height: 20), CupertinoButton.filled( key: copyKey, onPressed: code == null ? null : _copy, child: Row( mainAxisSize: MainAxisSize.min, children: [ Icon( _copied ? CupertinoIcons.checkmark : CupertinoIcons.doc_on_doc, ), const SizedBox(width: 8), Text(_copied ? 'Copied' : 'Copy code'), ], ), ), ], ), ), ), Padding( padding: const EdgeInsets.fromLTRB(32, 16, 32, 16), child: Text( 'Generated offline on this device. The code changes every day; ' 'pick another date if you need a code for a different day.', textAlign: TextAlign.center, style: TextStyle(color: secondary, fontSize: 13), ), ), ], ), ), ); } }