fix(Markdown): Do not crash the app if the link you've clicked could not be handled

This commit is contained in:
Artem Chepurnoy 2024-03-27 10:23:41 +02:00
parent 974889279d
commit 7cd468542e
No known key found for this signature in database
GPG Key ID: FAC37D0CF674043E
1 changed files with 31 additions and 0 deletions

View File

@ -2,14 +2,22 @@ package com.artemchep.keyguard.ui.markdown
import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalUriHandler
import com.artemchep.keyguard.common.model.ToastMessage
import com.artemchep.keyguard.common.usecase.ShowMessage
import com.halilibo.richtext.commonmark.Markdown import com.halilibo.richtext.commonmark.Markdown
import com.halilibo.richtext.markdown.BasicMarkdown import com.halilibo.richtext.markdown.BasicMarkdown
import com.halilibo.richtext.markdown.node.AstNode import com.halilibo.richtext.markdown.node.AstNode
import com.halilibo.richtext.ui.LinkClickHandler
import com.halilibo.richtext.ui.RichTextStyle import com.halilibo.richtext.ui.RichTextStyle
import com.halilibo.richtext.ui.material3.RichText import com.halilibo.richtext.ui.material3.RichText
import com.halilibo.richtext.ui.resolveDefaults import com.halilibo.richtext.ui.resolveDefaults
import com.halilibo.richtext.ui.string.RichTextStringStyle import com.halilibo.richtext.ui.string.RichTextStringStyle
import org.kodein.di.compose.rememberInstance
@Composable @Composable
fun MarkdownText( fun MarkdownText(
@ -20,6 +28,7 @@ fun MarkdownText(
RichText( RichText(
modifier = modifier, modifier = modifier,
style = richTextStyle, style = richTextStyle,
linkClickHandler = rememberGracefulLinkClickHandler(),
) { ) {
Markdown(markdown) Markdown(markdown)
} }
@ -34,11 +43,33 @@ fun MarkdownText(
RichText( RichText(
modifier = modifier, modifier = modifier,
style = richTextStyle, style = richTextStyle,
linkClickHandler = rememberGracefulLinkClickHandler(),
) { ) {
BasicMarkdown(markdown) BasicMarkdown(markdown)
} }
} }
@Composable
private fun rememberGracefulLinkClickHandler(): LinkClickHandler {
val showMessage by rememberInstance<ShowMessage>()
val updatedUriHandler by rememberUpdatedState(LocalUriHandler.current)
return remember {
LinkClickHandler { uri ->
try {
updatedUriHandler.openUri(uri)
} catch (e: Exception) {
val title = e.message
?: "Could not open a URI"
val msg = ToastMessage(
title = title,
type = ToastMessage.Type.ERROR,
)
showMessage.copy(msg)
}
}
}
}
@Composable @Composable
private fun getRichTextStyle(): RichTextStyle { private fun getRichTextStyle(): RichTextStyle {
return RichTextStyle().resolveDefaults().copy( return RichTextStyle().resolveDefaults().copy(