summaryrefslogtreecommitdiff
path: root/player-android/lib/screens/subscribe_dialog.dart
blob: c0c32fa1fe3bb93f758fee1946ceb5985f773e29 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
import 'package:flutter/material.dart';

import '../api/player_api_client.dart';
import '../utils/error_mappers.dart';

// ---------------------------------------------------------------------------
// showSubscribeDialog — public entry point
// ---------------------------------------------------------------------------

/// Opens the [_SubscribeDialog] as a modal dialog.
///
/// Returns the subscribed feed's set name on success, or `null` if the user
/// cancelled.  Separating the entry-point function from the widget (Single
/// Responsibility) means call sites never construct the dialog class directly —
/// they call this function and react to the returned value.
///
/// [client] must be an authenticated [PlayerApiClient]; no Dio import is
/// needed at the call site (Dependency Inversion Principle).
Future<String?> showSubscribeDialog(
  BuildContext context, {
  required PlayerApiClient client,
}) {
  return showDialog<String>(
    context: context,
    barrierDismissible: true,
    builder: (_) => _SubscribeDialog(client: client),
  );
}

// ---------------------------------------------------------------------------
// _SubscribeDialog
// ---------------------------------------------------------------------------

/// Modal dialog that collects a feed URL and optional set name, then calls
/// [PlayerApiClient.subscribePodcast] on submit.
///
/// Design notes:
///   - [StatefulWidget] (not [ConsumerStatefulWidget]) because the dialog
///     only needs the injected [client]; it does not read Riverpod providers
///     directly (Dependency Inversion: the caller owns the provider read).
///   - [mounted] guards protect every async continuation.
///   - No Dio import: error mapping is delegated to [podcastErrorMessage]
///     in `error_mappers.dart` (DIP/DRY).
///   - Clipboard/SnackBar logic lives in [_handleSuccess] (Single Responsibility)
///     so the submit orchestrator stays focused on flow control only.
///   - The widget is split into focused sub-builders so the [State] class
///     stays well under 50 lines.
class _SubscribeDialog extends StatefulWidget {
  const _SubscribeDialog({required this.client});

  final PlayerApiClient client;

  @override
  State<_SubscribeDialog> createState() => _SubscribeDialogState();
}

class _SubscribeDialogState extends State<_SubscribeDialog> {
  // Controller for the required feed URL text field.
  final _feedUrlController = TextEditingController();

  // Controller for the optional set-name text field.
  final _setNameController = TextEditingController();

  // True while the subscribePodcast API call is in flight; disables buttons.
  bool _isSubmitting = false;

  // Non-null when the last submit attempt failed.
  String? _error;

  @override
  void dispose() {
    _feedUrlController.dispose();
    _setNameController.dispose();
    super.dispose();
  }

  // ---------------------------------------------------------------------------
  // Actions
  // ---------------------------------------------------------------------------

  /// Validates inputs, calls [subscribePodcast], and delegates to
  /// [_handleSuccess] or displays an inline error.
  ///
  /// Acts as an orchestrator: validation → API call → [_handleSuccess] or
  /// error display.  SnackBar/Navigator logic stays in [_handleSuccess]
  /// (Single Responsibility) so each method has one reason to change.
  Future<void> _submit() async {
    if (_isSubmitting) return;

    final feedUrl = _feedUrlController.text.trim();
    if (feedUrl.isEmpty) {
      setState(() => _error = 'Feed URL is required.');
      return;
    }

    setState(() {
      _isSubmitting = true;
      _error = null;
    });

    try {
      final setName = _setNameController.text.trim();
      await widget.client.subscribePodcast(
        feedUrl: feedUrl,
        setName: setName.isEmpty ? null : setName,
      );

      if (!mounted) return;
      await _handleSuccess(context);
    } catch (e) {
      if (!mounted) return;
      setState(() {
        _error = podcastErrorMessage(e);
        _isSubmitting = false;
      });
    }
  }

  /// Closes the dialog and shows a success SnackBar.
  ///
  /// Extracted from [_submit] so the SnackBar/Navigator responsibility lives
  /// in one place (Single Responsibility).  Navigator and ScaffoldMessenger
  /// are captured before the first `await` so they are never accessed across
  /// an async gap via BuildContext (avoids use_build_context_synchronously).
  Future<void> _handleSuccess(BuildContext context) async {
    // Capture navigator and messenger before any async gap.
    final navigator = Navigator.of(context);
    final messenger = ScaffoldMessenger.of(context);
    final feedTitle = _feedUrlController.text.trim();

    // Close the dialog and pass back the feed URL as a success signal.
    navigator.pop(feedTitle);

    // Show a success SnackBar through the outer Scaffold's messenger.
    messenger.showSnackBar(
      const SnackBar(
        content: Text('Podcast subscribed. The feed will be fetched shortly.'),
        duration: Duration(seconds: 4),
      ),
    );
  }

  // ---------------------------------------------------------------------------
  // Build
  // ---------------------------------------------------------------------------

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      key: const Key('subscribe_dialog'),
      title: const Text('Subscribe to Podcast'),
      content: _buildContent(context),
      actions: _buildActions(context),
    );
  }

  /// Dialog body: feed URL field, set-name field, and optional error message.
  Widget _buildContent(BuildContext context) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        _FeedUrlField(controller: _feedUrlController),
        const SizedBox(height: 16),
        _SetNameField(controller: _setNameController),
        if (_error != null) ...[
          const SizedBox(height: 12),
          _ErrorText(message: _error!),
        ],
      ],
    );
  }

  /// Cancel and Subscribe action buttons.
  ///
  /// Both are disabled while [_isSubmitting] is true to prevent double-submit.
  List<Widget> _buildActions(BuildContext context) {
    return [
      TextButton(
        key: const Key('subscribe_cancel'),
        onPressed: _isSubmitting ? null : () => Navigator.of(context).pop(),
        child: const Text('Cancel'),
      ),
      FilledButton(
        key: const Key('subscribe_submit'),
        onPressed: _isSubmitting ? null : _submit,
        child: _isSubmitting
            ? const SizedBox(
                width: 18,
                height: 18,
                child: CircularProgressIndicator(strokeWidth: 2),
              )
            : const Text('Subscribe'),
      ),
    ];
  }
}

// ---------------------------------------------------------------------------
// _FeedUrlField
// ---------------------------------------------------------------------------

/// Required text field for the podcast feed URL.
///
/// Extracted as a stateless widget (Single Responsibility) so
/// [_SubscribeDialogState] stays concise and the field is independently
/// testable.
class _FeedUrlField extends StatelessWidget {
  const _FeedUrlField({required this.controller});

  final TextEditingController controller;

  @override
  Widget build(BuildContext context) {
    return TextField(
      key: const Key('subscribe_feed_url'),
      controller: controller,
      keyboardType: TextInputType.url,
      autocorrect: false,
      decoration: const InputDecoration(
        labelText: 'Feed URL',
        hintText: 'https://example.com/feed.rss',
        border: OutlineInputBorder(),
        isDense: true,
      ),
    );
  }
}

// ---------------------------------------------------------------------------
// _SetNameField
// ---------------------------------------------------------------------------

/// Optional text field for the podcast set name.
///
/// When left blank the server derives the name from the feed's own title.
/// Extracted as a stateless widget (SRP) for independent testability.
class _SetNameField extends StatelessWidget {
  const _SetNameField({required this.controller});

  final TextEditingController controller;

  @override
  Widget build(BuildContext context) {
    return TextField(
      key: const Key('subscribe_set_name'),
      controller: controller,
      decoration: const InputDecoration(
        labelText: 'Set name (optional)',
        hintText: 'Leave blank to use the feed title',
        border: OutlineInputBorder(),
        isDense: true,
      ),
    );
  }
}

// ---------------------------------------------------------------------------
// _ErrorText
// ---------------------------------------------------------------------------

/// Inline error message shown when the subscribePodcast API call fails.
///
/// Uses the error colour from [ColorScheme] for semantic consistency with
/// other error states in the app.
class _ErrorText extends StatelessWidget {
  const _ErrorText({required this.message});

  final String message;

  @override
  Widget build(BuildContext context) {
    return Text(
      message,
      key: const Key('subscribe_error'),
      style: Theme.of(context)
          .textTheme
          .bodySmall
          ?.copyWith(color: Theme.of(context).colorScheme.error),
    );
  }
}