summaryrefslogtreecommitdiff
path: root/app/src/main/java/org/terst/feedreader/ui/ReaderScreen.kt
blob: 1fe198e23326cb40718f14e749e9ff766533e224 (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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
package org.terst.feedreader.ui

import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.net.Uri
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Article
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.Bookmark
import androidx.compose.material.icons.filled.BookmarkBorder
import androidx.compose.material.icons.filled.CloudDone
import androidx.compose.material.icons.filled.CloudUpload
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material.icons.filled.OpenInBrowser
import androidx.compose.material.icons.outlined.Article
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.BottomAppBar
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import org.terst.feedreader.data.AppDatabase
import org.terst.feedreader.data.ArticleEntity
import org.terst.feedreader.data.FeedEntity
import org.terst.feedreader.data.ensureStandaloneArticle
import org.terst.feedreader.data.saveArticleToStash
import org.terst.feedreader.readability.ReaderExtractor
import java.net.URLEncoder

/**
 * Swipeable wrapper: snapshots the article-id order of the list this reader
 * was opened from (Unread/Saved/a specific feed) ONCE at entry, then pages
 * across that fixed queue. Deliberately a snapshot, not a live Flow -- opening
 * an article marks it read, which would otherwise drop it out of the live
 * Unread query mid-swipe and shift every subsequent page underneath the user.
 */
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun ReaderScreen(
    feedId: String,
    initialArticleId: String,
    onBack: () -> Unit,
    onOpenLink: (String) -> Unit,
    onOpenBrowser: (String) -> Unit
) {
    val context = LocalContext.current
    val db = remember { AppDatabase.get(context) }
    var articleIds by remember(feedId) { mutableStateOf<List<String>?>(null) }

    LaunchedEffect(feedId) {
        val cutoff = System.currentTimeMillis() - RECENT_WINDOW_MS
        val flow = when (feedId) {
            UNREAD_FEED_ID -> db.articleDao().observeUnread(cutoff)
            OLDER_FEED_ID -> db.articleDao().observeOlderUnread(cutoff)
            SAVED_FEED_ID -> db.articleDao().observeSaved()
            else -> db.articleDao().observeByFeed(feedId)
        }
        articleIds = flow.first().map { it.id }
    }

    val ids = articleIds
    if (ids == null) {
        Box(modifier = Modifier.fillMaxSize()) {
            CircularProgressIndicator(modifier = Modifier.align(Alignment.Center))
        }
        return
    }
    // The article may have been opened from somewhere not in this queue (shouldn't normally
    // happen, but fall back to a single-item queue rather than crashing on indexOfFirst = -1).
    val safeIds = if (ids.contains(initialArticleId)) ids else listOf(initialArticleId)
    val initialIndex = safeIds.indexOf(initialArticleId).coerceAtLeast(0)
    val pagerState = rememberPagerState(initialPage = initialIndex) { safeIds.size }
    val scope = rememberCoroutineScope()

    // Swipe-to-next-article is gone -- two different approaches to keeping it from
    // interfering with WebView scrolling (an orientation-aware Compose gesture detector,
    // then a passive native touch listener) were tried and neither actually resolved the
    // reported jerkiness, and the second one broke swipe outright. Explicit Previous/Next
    // buttons in the bottom bar replace it: no ambiguity with scrolling at all, since
    // there's no gesture to disambiguate in the first place.
    val currentPage = pagerState.currentPage
    val hasPrevious = currentPage > 0
    val hasNext = currentPage < safeIds.size - 1
    // Marking read happens HERE (moving to another article), not on open -- backing out
    // to the list without paging past an article leaves it unread. Only Next/Previous
    // count as "moved away from it"; exiting via the back arrow deliberately doesn't.
    fun goToPreviousArticle() {
        val leavingId = safeIds[pagerState.currentPage]
        scope.launch {
            db.articleDao().setRead(leavingId, true)
            pagerState.animateScrollToPage((pagerState.currentPage - 1).coerceAtLeast(0))
        }
    }
    fun goToNextArticle() {
        val leavingId = safeIds[pagerState.currentPage]
        scope.launch {
            db.articleDao().setRead(leavingId, true)
            pagerState.animateScrollToPage((pagerState.currentPage + 1).coerceAtMost(safeIds.size - 1))
        }
    }
    // "I looked, but I'm not done with this one" -- advances the same as Next, just without
    // the implicit setRead(true) that moving on normally carries.
    fun goToNextArticleKeepUnread() {
        scope.launch {
            pagerState.animateScrollToPage((pagerState.currentPage + 1).coerceAtMost(safeIds.size - 1))
        }
    }

    HorizontalPager(state = pagerState, userScrollEnabled = false, modifier = Modifier.fillMaxSize()) { page ->
        ReaderContent(
            articleId = safeIds[page],
            onBack = onBack,
            onOpenLink = onOpenLink,
            onOpenBrowser = onOpenBrowser,
            hasPrevious = hasPrevious,
            hasNext = hasNext,
            onPrevious = ::goToPreviousArticle,
            onNext = ::goToNextArticle,
            onNextKeepUnread = ::goToNextArticleKeepUnread
        )
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun ReaderContent(
    articleId: String,
    onBack: () -> Unit,
    onOpenLink: (String) -> Unit,
    onOpenBrowser: (String) -> Unit,
    hasPrevious: Boolean,
    hasNext: Boolean,
    onPrevious: () -> Unit,
    onNext: () -> Unit,
    onNextKeepUnread: () -> Unit
) {
    val context = LocalContext.current
    val db = remember { AppDatabase.get(context) }
    val scope = rememberCoroutineScope()
    val snackbarHostState = remember { SnackbarHostState() }

    var article by remember(articleId) { mutableStateOf<ArticleEntity?>(null) }
    var feed by remember(articleId) { mutableStateOf<FeedEntity?>(null) }
    var feedContent by remember(articleId) { mutableStateOf<String?>(null) }
    var readerContent by remember(articleId) { mutableStateOf<String?>(null) }
    var isReaderMode by remember(articleId) { mutableStateOf(false) }
    var isExtracting by remember(articleId) { mutableStateOf(false) }
    var isSaving by remember(articleId) { mutableStateOf(false) }
    var moreMenuExpanded by remember(articleId) { mutableStateOf(false) }
    var showBugReportDialog by remember(articleId) { mutableStateOf(false) }
    var bugReportDescription by remember(articleId) { mutableStateOf("") }
    var longPressedLink by remember(articleId) { mutableStateOf<String?>(null) }

    LaunchedEffect(articleId) {
        val loaded = db.articleDao().getById(articleId) ?: return@LaunchedEffect
        article = loaded
        // Deliberately NOT marking read here -- see ReaderScreen.goToNextArticle/
        // goToPreviousArticle, which is where "read" actually gets set now.
        val loadedFeed = loaded.feedId?.let { db.feedDao().getById(it) }
        feed = loadedFeed

        feedContent = loaded.feedContentHtml
        readerContent = loaded.extractedContent

        // Reader mode is NEVER heuristic/automatic (no more "content looks thin, switch
        // for you") -- it strictly follows the feed's persisted, explicitly-set opt-in.
        // Once a feed has it on, articles from it default to the extracted view and
        // auto-extract on open (that's the point of persisting it per-feed: no re-tapping
        // per article), but nothing here ever turns it on by itself.
        if (loadedFeed?.readerModeEnabled == true) {
            isReaderMode = true
            if (readerContent == null) {
                isExtracting = true
                val extracted = ReaderExtractor.extract(context, loaded.link)
                isExtracting = false
                extracted?.content?.let {
                    readerContent = it
                    db.articleDao().setExtractedContent(articleId, it)
                }
            }
        }
    }

    // The toggle now sets reader mode for the ARTICLE'S FEED, persisted immediately, with
    // a confirmation snackbar -- not a per-article, this-session-only view flip. Tapping it
    // is the one and only way reader mode ever turns on.
    fun toggleFeedReaderMode() {
        val f = feed ?: return
        val a = article ?: return
        val newEnabled = !f.readerModeEnabled
        feed = f.copy(readerModeEnabled = newEnabled)
        scope.launch {
            db.feedDao().update(f.copy(readerModeEnabled = newEnabled))
            val feedLabel = f.title.ifBlank { "this feed" }
            if (newEnabled) {
                if (readerContent == null) {
                    isExtracting = true
                    val extracted = ReaderExtractor.extract(context, a.link)
                    isExtracting = false
                    val content = extracted?.content
                    if (content != null) {
                        readerContent = content
                        db.articleDao().setExtractedContent(articleId, content)
                    }
                }
                isReaderMode = true
                snackbarHostState.showSnackbar("Reader mode enabled for $feedLabel")
            } else {
                isReaderMode = false
                readerContent = null
                db.articleDao().clearExtractedContent(articleId)
                snackbarHostState.showSnackbar("Reader mode disabled for $feedLabel")
            }
        }
    }

    Scaffold(
        topBar = {
            TopAppBar(
                title = {
                    Column {
                        Text(
                            article?.title.orEmpty(),
                            maxLines = 1,
                            overflow = TextOverflow.Ellipsis,
                            style = MaterialTheme.typography.titleMedium
                        )
                        feed?.title?.let {
                            Text(
                                it,
                                maxLines = 1,
                                overflow = TextOverflow.Ellipsis,
                                style = MaterialTheme.typography.labelSmall,
                                color = MaterialTheme.colorScheme.onSurfaceVariant
                            )
                        }
                    }
                },
                navigationIcon = {
                    IconButton(onClick = onBack) {
                        Icon(Icons.Default.ArrowBack, contentDescription = "Back")
                    }
                },
                actions = {
                    val currentArticle = article
                    // Sets reader mode for the whole feed (persisted), not just this article --
                    // shown whenever the article belongs to an actual subscribed feed.
                    if (feed != null) {
                        IconButton(enabled = !isExtracting, onClick = { toggleFeedReaderMode() }) {
                            Icon(
                                if (feed?.readerModeEnabled == true) Icons.Filled.Article else Icons.Outlined.Article,
                                contentDescription = if (feed?.readerModeEnabled == true)
                                    "Reader mode enabled for this feed -- tap to disable"
                                else
                                    "Reader mode disabled for this feed -- tap to enable"
                            )
                        }
                    }
                    // Purely local: just flips isSaved (shows up in the Saved list). Does NOT
                    // touch Stash -- that's a separate, explicit action in the overflow menu,
                    // since archiving to Stash is a heavier/networked action the user should
                    // trigger on purpose.
                    IconButton(onClick = {
                        val a = currentArticle ?: return@IconButton
                        val newSaved = !a.isSaved
                        article = a.copy(isSaved = newSaved)
                        scope.launch { db.articleDao().setSaved(a.id, newSaved) }
                    }) {
                        Icon(
                            if (currentArticle?.isSaved == true) Icons.Default.Bookmark else Icons.Default.BookmarkBorder,
                            contentDescription = "Save locally"
                        )
                    }
                    IconButton(onClick = { moreMenuExpanded = true }) {
                        Icon(Icons.Default.MoreVert, contentDescription = "More")
                    }
                    DropdownMenu(expanded = moreMenuExpanded, onDismissRequest = { moreMenuExpanded = false }) {
                        DropdownMenuItem(
                            leadingIcon = { Icon(Icons.Default.OpenInBrowser, contentDescription = null) },
                            text = { Text("Open original") },
                            onClick = {
                                moreMenuExpanded = false
                                val a = currentArticle ?: return@DropdownMenuItem
                                context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(a.link)))
                            }
                        )
                        DropdownMenuItem(
                            enabled = !isSaving,
                            leadingIcon = {
                                Icon(
                                    if (currentArticle?.stashArtifactId != null) Icons.Default.CloudDone else Icons.Default.CloudUpload,
                                    contentDescription = null
                                )
                            },
                            text = { Text(if (currentArticle?.stashArtifactId != null) "Saved to Stash" else "Save to Stash") },
                            onClick = {
                                moreMenuExpanded = false
                                val a = currentArticle ?: return@DropdownMenuItem
                                isSaving = true
                                scope.launch {
                                    val outcome = saveArticleToStash(context, db, a.id, a.link, a.title)
                                    outcome.artifactId?.let { article = a.copy(stashArtifactId = it) }
                                    snackbarHostState.showSnackbar(outcome.message)
                                    isSaving = false
                                }
                            }
                        )
                        DropdownMenuItem(
                            text = { Text("Mark unread") },
                            onClick = {
                                moreMenuExpanded = false
                                val a = currentArticle ?: return@DropdownMenuItem
                                article = a.copy(isRead = false)
                                scope.launch {
                                    db.articleDao().setRead(a.id, false)
                                    snackbarHostState.showSnackbar("Marked unread")
                                }
                            }
                        )
                        // A real (JS-on) browser, not the extraction pipeline -- search results
                        // and login pages need actual interaction, not a Readability pass.
                        DropdownMenuItem(
                            text = { Text("Find another source") },
                            onClick = {
                                moreMenuExpanded = false
                                val a = currentArticle ?: return@DropdownMenuItem
                                val query = URLEncoder.encode(a.title, "UTF-8")
                                onOpenBrowser("https://www.google.com/search?q=$query")
                            }
                        )
                        DropdownMenuItem(
                            text = { Text("Log in to this site") },
                            onClick = {
                                moreMenuExpanded = false
                                val a = currentArticle ?: return@DropdownMenuItem
                                onOpenBrowser(a.link)
                            }
                        )
                        // Forces a fresh fetch + Readability pass, overwriting whatever's
                        // cached -- for when extraction came back thin, stale, or broken
                        // (e.g. a YouTube thumbnail that failed to resolve) and simply hasn't
                        // been retried since whatever caused that.
                        DropdownMenuItem(
                            enabled = !isExtracting,
                            text = { Text("Re-download and re-extract") },
                            onClick = {
                                moreMenuExpanded = false
                                val a = currentArticle ?: return@DropdownMenuItem
                                scope.launch {
                                    isExtracting = true
                                    val extracted = ReaderExtractor.extract(context, a.link)
                                    isExtracting = false
                                    val content = extracted?.content
                                    if (content != null) {
                                        readerContent = content
                                        isReaderMode = true
                                        db.articleDao().setExtractedContent(a.id, content)
                                        snackbarHostState.showSnackbar("Re-extracted")
                                    } else {
                                        snackbarHostState.showSnackbar("Re-extraction failed")
                                    }
                                }
                            }
                        )
                        DropdownMenuItem(
                            text = { Text("Report bug") },
                            onClick = {
                                moreMenuExpanded = false
                                showBugReportDialog = true
                            }
                        )
                    }
                }
            )
        },
        bottomBar = {
            BottomAppBar {
                TextButton(onClick = onPrevious, enabled = hasPrevious, modifier = Modifier.weight(1f)) {
                    Text("Previous")
                }
                // Advances like Next, but skips the implicit "mark read" that moving on
                // normally carries -- for "I looked, but I'm not done with this one yet."
                TextButton(onClick = onNextKeepUnread, enabled = hasNext, modifier = Modifier.weight(1f)) {
                    Text("Keep unread")
                }
                TextButton(onClick = onNext, enabled = hasNext, modifier = Modifier.weight(1f)) {
                    Text("Next")
                }
            }
        },
        snackbarHost = { SnackbarHost(snackbarHostState) }
    ) { padding ->
        if (showBugReportDialog) {
            val a = article
            AlertDialog(
                onDismissRequest = { showBugReportDialog = false },
                title = { Text("Report bug") },
                text = {
                    Column {
                        Text("Describe what happened. Copies article/feed state along with it so it can be reproduced.")
                        Spacer(modifier = Modifier.height(12.dp))
                        OutlinedTextField(
                            value = bugReportDescription,
                            onValueChange = { bugReportDescription = it },
                            label = { Text("Description") },
                            modifier = Modifier.fillMaxWidth()
                        )
                    }
                },
                confirmButton = {
                    TextButton(onClick = {
                        val report = buildString {
                            appendLine("Feeds bug report")
                            appendLine("Description: ${bugReportDescription.ifBlank { "(none provided)" }}")
                            appendLine("Article title: ${a?.title}")
                            appendLine("Article URL: ${a?.link}")
                            appendLine("Article id: ${a?.id}")
                            appendLine("Feed: ${feed?.title} (${feed?.id})")
                            appendLine("Feed readerModeEnabled: ${feed?.readerModeEnabled}")
                            appendLine("Session isReaderMode: $isReaderMode")
                            appendLine("isSaved: ${a?.isSaved}, stashArtifactId: ${a?.stashArtifactId}")
                            appendLine("extractedContent cached: ${readerContent != null}")
                        }
                        val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
                        clipboard.setPrimaryClip(ClipData.newPlainText("Bug report", report))
                        showBugReportDialog = false
                        scope.launch { snackbarHostState.showSnackbar("Copied to clipboard") }
                    }) { Text("Copy") }
                },
                dismissButton = {
                    TextButton(onClick = { showBugReportDialog = false }) { Text("Cancel") }
                }
            )
        }
        longPressedLink?.let { url ->
            LinkActionsDialog(
                url = url,
                onDismiss = { longPressedLink = null },
                onOpenInBrowser = { context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url))) },
                onShare = {
                    val send = Intent(Intent.ACTION_SEND).apply {
                        type = "text/plain"
                        putExtra(Intent.EXTRA_TEXT, url)
                    }
                    context.startActivity(Intent.createChooser(send, null))
                },
                onSaveToStash = {
                    scope.launch {
                        val entity = ensureStandaloneArticle(context, db, url)
                        val outcome = saveArticleToStash(context, db, entity.id, url, entity.title)
                        snackbarHostState.showSnackbar(outcome.message)
                    }
                },
                onSaveForLater = {
                    scope.launch {
                        val entity = ensureStandaloneArticle(context, db, url)
                        if (!entity.isSaved) db.articleDao().setSaved(entity.id, true)
                        snackbarHostState.showSnackbar("Saved for later")
                    }
                }
            )
        }
        Box(modifier = Modifier.fillMaxSize().padding(padding)) {
            val content = if (isReaderMode) readerContent else (feedContent ?: readerContent)
            val baseUrl = article?.link
            if (content != null) {
                // AndroidView's update lambda reruns on every recomposition of this
                // composable -- including ones unrelated to content, like isSaving
                // flipping while a Stash save is in flight. Reloading the WebView's HTML
                // on those unrelated recompositions was resetting scroll position mid-swipe,
                // which is what made scrolling feel unsmooth/janky. Track what's actually
                // loaded and only reload when the content string itself changes.
                val loadedContent = remember(articleId) { mutableStateOf<String?>(null) }
                AndroidView(
                    modifier = Modifier.fillMaxSize(),
                    factory = { ctx ->
                        newReaderWebView(ctx, onOpenLink, onLongPressLink = { longPressedLink = it }).apply {
                            loadDataWithBaseURL(baseUrl, wrapReaderHtml(content, article?.title), "text/html", "UTF-8", null)
                            loadedContent.value = content
                        }
                    },
                    update = { webView ->
                        if (loadedContent.value != content) {
                            webView.loadDataWithBaseURL(baseUrl, wrapReaderHtml(content, article?.title), "text/html", "UTF-8", null)
                            loadedContent.value = content
                        }
                    },
                    // AndroidView does not destroy() the underlying WebView on its own --
                    // without this, swiping through many articles (each page holding its own
                    // WebView) leaks a WebView's native resources per page and eventually
                    // exhausts memory over a long reading session.
                    onRelease = { webView -> webView.destroy() }
                )
            } else if (isExtracting) {
                CircularProgressIndicator(modifier = Modifier.align(Alignment.Center))
            }
        }
    }
}