Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view

This file was deleted.

This file was deleted.

140 changes: 101 additions & 39 deletions app/src/main/kotlin/com/hippo/ehviewer/ui/main/GalleryComment.kt
Original file line number Diff line number Diff line change
@@ -1,33 +1,96 @@
package com.hippo.ehviewer.ui.main

import android.text.Html
import android.text.TextUtils
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.text.InlineTextContent
import androidx.compose.material3.Card
import androidx.compose.material3.LocalContentColor
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ProvideTextStyle
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.neverEqualPolicy
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.res.dimensionResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.LinkAnnotation
import androidx.compose.ui.text.LinkInteractionListener
import androidx.compose.ui.text.Placeholder
import androidx.compose.ui.text.PlaceholderVerticalAlign
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.TextLinkStyles
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.fromHtml
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.Density
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.core.text.parseAsHtml
import coil3.compose.AsyncImage
import coil3.decode.DecodeUtils
import coil3.size.Scale
import com.hippo.ehviewer.R
import com.hippo.ehviewer.client.data.GalleryComment
import com.hippo.ehviewer.ui.legacy.CoilImageGetter
import com.hippo.ehviewer.ui.legacy.LinkifyTextView
import com.hippo.ehviewer.ui.tools.thenIf
import com.hippo.ehviewer.util.ReadableTime
import com.hippo.ehviewer.util.toIntOrDefault
import kotlin.math.roundToInt

private const val IMAGE_OBJ = ''
private const val INLINE_CONTENT_TAG = "androidx.compose.foundation.text.inlineContent"
private val IMAGE_PATTERN =
"(?:<a href=\"([^\"]+)\">)?<img src=\"((?:[^-]+-){2}(\\d+)-(\\d+)-[^_]+_([^.]+)[^\"]+)\"".toRegex()

private fun breakToTextAndInlineContent(
origin: String,
text: AnnotatedString,
density: Density,
onUrlClick: (String) -> Unit,
): Pair<AnnotatedString, Map<String, InlineTextContent>> = with(density) {
val urls = IMAGE_PATTERN.findAll(origin)
val iter = urls.iterator()
if (!iter.hasNext()) return text to emptyMap()
var currentOfs = 0
val inlineContent = mutableMapOf<String, InlineTextContent>()
return buildAnnotatedString {
append(text)
while (true) {
val index = text.text.indexOf(IMAGE_OBJ, currentOfs)
if (index == -1) break
val key = "$index"
addStringAnnotation(INLINE_CONTENT_TAG, key, index, index + 1)
val groupValues = iter.next().groupValues
val url = groupValues[1]
val imageUrl = groupValues[2]
val srcWidth = groupValues[3].toInt()
val srcHeight = groupValues[4].toInt()
val dstWidth = groupValues[5].toIntOrDefault(200)
val dstHeight = dstWidth / 2 * 3
val multiplier = DecodeUtils.computeSizeMultiplier(srcWidth, srcHeight, dstWidth, dstHeight, Scale.FIT)

// TODO: Use dynamic inline content
// https://issuetracker.google.com/294110693
inlineContent[key] = InlineTextContent(
Placeholder(
width = (srcWidth * multiplier).roundToInt().toSp(),
height = (srcHeight * multiplier).roundToInt().toSp(),
placeholderVerticalAlign = PlaceholderVerticalAlign.Top,
),
) {
AsyncImage(
model = imageUrl,
contentDescription = null,
modifier = Modifier.thenIf(url.isNotEmpty()) {
clickable { onUrlClick(url) }
},
)
}
currentOfs = index + 1
}
} to inlineContent
}

@Composable
fun GalleryCommentCard(
Expand All @@ -37,19 +100,10 @@ fun GalleryCommentCard(
onUserClick: () -> Unit,
onUrlClick: (String) -> Unit,
maxLines: Int = Int.MAX_VALUE,
ellipsis: Boolean = false,
processComment: @Composable (GalleryComment, Html.ImageGetter) -> CharSequence = { c, ig -> c.comment.parseAsHtml(imageGetter = ig) },
overflow: TextOverflow = TextOverflow.Clip,
processComment: @Composable (GalleryComment, TextLinkStyles, LinkInteractionListener) -> AnnotatedString = { c, s, l -> AnnotatedString.fromHtml(c.comment, s, l) },
) = with(comment) {
val targetUrl = remember { mutableStateOf<String?>(null) }
Card(
onClick = {
targetUrl.value?.also {
onUrlClick(it)
targetUrl.value = null
} ?: onCardClick()
},
modifier = modifier,
) {
Card(onClick = onCardClick, modifier = modifier) {
val margin = dimensionResource(id = R.dimen.keyline_margin)
Row(
modifier = Modifier.padding(horizontal = margin, vertical = 8.dp).fillMaxWidth(),
Expand All @@ -66,23 +120,31 @@ fun GalleryCommentCard(
)
}
}
val textColor = LocalContentColor.current.toArgb()
val linkTextColor = MaterialTheme.colorScheme.primary.toArgb()
val redrawSignal = remember { mutableStateOf(Unit, neverEqualPolicy()) }
val commentText = processComment(comment, CoilImageGetter { redrawSignal.value = Unit })
AndroidView(
factory = { context ->
LinkifyTextView(context) { targetUrl.value = it }.apply {
setTextColor(textColor)
setLinkTextColor(linkTextColor)
this.maxLines = maxLines
if (ellipsis) ellipsize = TextUtils.TruncateAt.END
}
},
Column(
modifier = Modifier.padding(start = margin, end = margin, bottom = 8.dp),
) { view ->
view.text = commentText
redrawSignal.value
) {
ProvideTextStyle(value = MaterialTheme.typography.bodyMedium) {
val linkColor = MaterialTheme.colorScheme.primary
val processed = processComment(
comment,
TextLinkStyles(style = SpanStyle(color = linkColor)),
) { link ->
check(link is LinkAnnotation.Url)
onUrlClick(link.url)
}
val (text, inlineContent) = breakToTextAndInlineContent(
comment.comment,
processed,
LocalDensity.current,
onUrlClick,
)
Text(
text = text,
maxLines = maxLines,
overflow = overflow,
inlineContent = inlineContent,
)
}
}
}
}
Original file line number Diff line number Diff line change
@@ -1,12 +1,5 @@
package com.hippo.ehviewer.ui.screen

import android.graphics.Typeface
import android.text.Html
import android.text.Spannable
import android.text.style.ForegroundColorSpan
import android.text.style.RelativeSizeSpan
import android.text.style.StyleSpan
import android.text.style.URLSpan
import androidx.compose.animation.AnimatedVisibilityScope
import androidx.compose.animation.Crossfade
import androidx.compose.foundation.layout.Arrangement
Expand Down Expand Up @@ -58,7 +51,6 @@ import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.layout.layout
import androidx.compose.ui.layout.onGloballyPositioned
Expand All @@ -69,15 +61,20 @@ import androidx.compose.ui.platform.LocalTextToolbar
import androidx.compose.ui.res.dimensionResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.LinkAnnotation
import androidx.compose.ui.text.LinkInteractionListener
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.TextLinkStyles
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.fromHtml
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.unit.Constraints
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.em
import androidx.compose.ui.unit.max
import androidx.compose.ui.util.lerp
import androidx.core.text.buildSpannedString
import androidx.core.text.getSpans
import androidx.core.text.inSpans
import androidx.core.text.parseAsHtml
import com.hippo.ehviewer.R
import com.hippo.ehviewer.Settings
Expand Down Expand Up @@ -109,8 +106,8 @@ import com.ramcosta.composedestinations.navigation.DestinationsNavigator
import eu.kanade.tachiyomi.util.lang.launchIO
import eu.kanade.tachiyomi.util.lang.withUIContext
import eu.kanade.tachiyomi.util.system.logcat
import kotlin.collections.forEach
import kotlin.math.roundToInt
import kotlin.sequences.forEach
import kotlinx.coroutines.launch
import moe.tarsin.coroutines.runSuspendCatching

Expand All @@ -119,34 +116,31 @@ private val URL_PATTERN = Regex("(http|https)://[a-z0-9A-Z%-]+(\\.[a-z0-9A-Z%-]+
@Composable
fun processComment(
comment: GalleryComment,
imageGetter: Html.ImageGetter,
) = comment.comment.parseAsHtml(imageGetter = imageGetter).let { text ->
buildSpannedString {
linkStyle: TextLinkStyles,
onLinkClick: LinkInteractionListener,
) = AnnotatedString.fromHtml(comment.comment, linkStyle, onLinkClick).let { text ->
buildAnnotatedString {
val onSurfaceVariant = MaterialTheme.colorScheme.onSurfaceVariant
append(text)
URL_PATTERN.findAll(text).forEach { result ->
val start = result.range.first
val end = result.range.last + 1
if (getSpans<URLSpan>(start, end).isEmpty()) {
setSpan(URLSpan(result.groupValues[0]), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
if (!text.hasLinkAnnotations(start, end)) {
addLink(LinkAnnotation.Url(result.groupValues[0], linkStyle, onLinkClick), start, end)
}
}
val color = MaterialTheme.colorScheme.onSurfaceVariant.toArgb()
val spans = arrayOf(
RelativeSizeSpan(0.8f),
StyleSpan(Typeface.BOLD),
ForegroundColorSpan(color),
)
val style = SpanStyle(fontSize = 0.8f.em, fontWeight = FontWeight.Bold, color = onSurfaceVariant)
if (comment.id != 0L && comment.score != 0) {
val score = comment.score
val scoreString = if (score > 0) "+$score" else score.toString()
append(" ")
inSpans(*spans) {
withStyle(style) {
append(scoreString)
}
}
if (comment.lastEdited != 0L) {
append("\n\n")
inSpans(*spans) {
withStyle(style) {
append(
stringResource(
R.string.last_edited,
Expand Down Expand Up @@ -406,7 +400,7 @@ fun AnimatedVisibilityScope.GalleryCommentsScreen(gid: Long, navigator: Destinat
if (!jumpToReaderByPage(it, galleryDetail)) if (!navWithUrl(it)) openBrowser(it)
}
},
processComment = { c, ig -> processComment(c, ig) },
processComment = { c, s, l -> processComment(c, s, l) },
)
}
if (comments.hasMore) {
Expand Down
Loading