Skip to content

Commit

Permalink
[VMD-Flow] VMDHtmlTextViewModel / VMDHtmlText (#196)
Browse files Browse the repository at this point in the history
Renders html text (a subset of html tags) in a Text component in switui / compose. Rendering differ slightly on both platforms but is generally more performant than using a full fledged webview.
  • Loading branch information
npresseault authored Oct 17, 2023
1 parent 0d267a7 commit ef0983d
Show file tree
Hide file tree
Showing 24 changed files with 762 additions and 3 deletions.
1 change: 1 addition & 0 deletions trikot-streams/streams/api/android/streams.api
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,7 @@ public final class com/mirego/trikot/streams/reactive/PublisherExtensionsKt {
public static final fun scan (Lorg/reactivestreams/Publisher;Lkotlin/jvm/functions/Function2;)Lorg/reactivestreams/Publisher;
public static final fun scanWith (Lorg/reactivestreams/Publisher;Lkotlin/jvm/functions/Function0;Lkotlin/jvm/functions/Function2;)Lorg/reactivestreams/Publisher;
public static final fun shared (Lorg/reactivestreams/Publisher;)Lorg/reactivestreams/Publisher;
public static final fun skip (Lorg/reactivestreams/Publisher;J)Lorg/reactivestreams/Publisher;
public static final fun startWith (Lorg/reactivestreams/Publisher;Ljava/lang/Object;)Lorg/reactivestreams/Publisher;
public static final fun subscribe (Lorg/reactivestreams/Publisher;Lcom/mirego/trikot/streams/cancellable/CancellableManager;Lkotlin/jvm/functions/Function1;)V
public static final fun subscribe (Lorg/reactivestreams/Publisher;Lcom/mirego/trikot/streams/cancellable/CancellableManager;Lkotlin/jvm/functions/Function1;Lkotlin/jvm/functions/Function1;)V
Expand Down
1 change: 1 addition & 0 deletions trikot-streams/streams/api/jvm/streams.api
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,7 @@ public final class com/mirego/trikot/streams/reactive/PublisherExtensionsKt {
public static final fun scan (Lorg/reactivestreams/Publisher;Lkotlin/jvm/functions/Function2;)Lorg/reactivestreams/Publisher;
public static final fun scanWith (Lorg/reactivestreams/Publisher;Lkotlin/jvm/functions/Function0;Lkotlin/jvm/functions/Function2;)Lorg/reactivestreams/Publisher;
public static final fun shared (Lorg/reactivestreams/Publisher;)Lorg/reactivestreams/Publisher;
public static final fun skip (Lorg/reactivestreams/Publisher;J)Lorg/reactivestreams/Publisher;
public static final fun startWith (Lorg/reactivestreams/Publisher;Ljava/lang/Object;)Lorg/reactivestreams/Publisher;
public static final fun subscribe (Lorg/reactivestreams/Publisher;Lcom/mirego/trikot/streams/cancellable/CancellableManager;Lkotlin/jvm/functions/Function1;)V
public static final fun subscribe (Lorg/reactivestreams/Publisher;Lcom/mirego/trikot/streams/cancellable/CancellableManager;Lkotlin/jvm/functions/Function1;Lkotlin/jvm/functions/Function1;)V
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -283,7 +283,7 @@ fun <T, R> Publisher<T>.scanWith(
}

/** Suppress the first n items emitted by a Publisher **/
internal fun <T> Publisher<T>.skip(n: Long) = SkipProcessor(this, n)
fun <T> Publisher<T>.skip(n: Long): Publisher<T> = SkipProcessor(this, n)

/** Periodically looks at publisher and emits whichever item it has most recently emitted since the previous sampling. **/
fun <T> Publisher<T>.sample(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,10 @@ public final class com/mirego/trikot/viewmodels/declarative/compose/viewmodel/VM
public static final fun VMDDropDownMenuItem (Lcom/mirego/trikot/viewmodels/declarative/components/VMDPickerViewModel;Lcom/mirego/trikot/viewmodels/declarative/components/VMDPickerItemViewModel;ILandroidx/compose/ui/Modifier;Lkotlin/jvm/functions/Function0;Landroidx/compose/foundation/layout/PaddingValues;Landroidx/compose/foundation/interaction/MutableInteractionSource;Lkotlin/jvm/functions/Function5;Landroidx/compose/runtime/Composer;II)V
}

public final class com/mirego/trikot/viewmodels/declarative/compose/viewmodel/VMDHtmlTextKt {
public static final fun VMDHtmlText-VhcvRP8 (Lcom/mirego/trikot/viewmodels/declarative/components/VMDHtmlTextViewModel;Landroidx/compose/ui/Modifier;Landroidx/compose/ui/text/TextStyle;ZIILkotlin/jvm/functions/Function1;ILandroidx/compose/ui/text/SpanStyle;Landroidx/compose/runtime/Composer;II)V
}

public final class com/mirego/trikot/viewmodels/declarative/compose/viewmodel/VMDImageKt {
public static final fun LocalImage (Lcom/mirego/trikot/viewmodels/declarative/properties/VMDImageResource;Landroidx/compose/ui/Modifier;Landroidx/compose/ui/Alignment;Landroidx/compose/ui/layout/ContentScale;FLandroidx/compose/ui/graphics/ColorFilter;Ljava/lang/String;Landroidx/compose/runtime/Composer;II)V
public static final fun RemoteImage (Landroidx/compose/ui/Modifier;Ljava/lang/String;Lcom/mirego/trikot/viewmodels/declarative/properties/VMDImageResource;Lkotlin/jvm/functions/Function5;Landroidx/compose/ui/Alignment;Landroidx/compose/ui/layout/ContentScale;Landroidx/compose/ui/graphics/ColorFilter;Ljava/lang/String;ZLkotlin/jvm/functions/Function1;Landroidx/compose/runtime/Composer;II)V
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package com.mirego.trikot.viewmodels.declarative.compose.viewmodel

import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.TextLayoutResult
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.text.style.TextOverflow
import androidx.core.text.HtmlCompat
import com.mirego.trikot.viewmodels.declarative.components.VMDHtmlTextViewModel
import com.mirego.trikot.viewmodels.declarative.compose.extensions.isOverridingAlpha
import com.mirego.trikot.viewmodels.declarative.compose.extensions.observeAsState
import com.mirego.trikot.viewmodels.declarative.compose.extensions.vmdModifier
import com.mirego.trikot.viewmodels.declarative.compose.viewmodel.internal.html.HtmlText
import com.mirego.trikot.viewmodels.declarative.compose.viewmodel.internal.html.linkTextColor

@Composable
fun VMDHtmlText(
viewModel: VMDHtmlTextViewModel,
modifier: Modifier = Modifier,
style: TextStyle = TextStyle.Default,
softWrap: Boolean = true,
overflow: TextOverflow = TextOverflow.Clip,
maxLines: Int = Int.MAX_VALUE,
onTextLayout: (TextLayoutResult) -> Unit = {},
flags: Int = HtmlCompat.FROM_HTML_MODE_COMPACT,
urlSpanStyle: SpanStyle = SpanStyle(
color = linkTextColor(),
textDecoration = TextDecoration.Underline,
),
) {
val textViewModel by viewModel.observeAsState(excludedProperties = if (modifier.isOverridingAlpha()) listOf(viewModel::isHidden) else emptyList())

HtmlText(
text = viewModel.html,
modifier = modifier.vmdModifier(textViewModel),
style = style,
softWrap = softWrap,
overflow = overflow,
maxLines = maxLines,
onTextLayout = onTextLayout,
linkClicked = viewModel.urlActionBlock,
flags = flags,
urlSpanStyle = urlSpanStyle,
)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/*
* Copyright 2023 compose-html
* https://github.com/viluahealthcare/compose-html
*
* Modified for Trikot
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mirego.trikot.viewmodels.declarative.compose.viewmodel.internal.html

import android.text.style.ForegroundColorSpan
import android.text.style.StrikethroughSpan
import android.text.style.UnderlineSpan
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.style.TextDecoration

internal fun UnderlineSpan.spanStyle(): SpanStyle =
SpanStyle(textDecoration = TextDecoration.Underline)

internal fun ForegroundColorSpan.spanStyle(): SpanStyle =
SpanStyle(color = Color(foregroundColor))

internal fun StrikethroughSpan.spanStyle(): SpanStyle =
SpanStyle(textDecoration = TextDecoration.LineThrough)
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
/*
* Copyright 2023 compose-html
* https://github.com/viluahealthcare/compose-html
*
* Modified for Trikot
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mirego.trikot.viewmodels.declarative.compose.viewmodel.internal.html

import android.text.style.BulletSpan
import android.text.style.ForegroundColorSpan
import android.text.style.RelativeSizeSpan
import android.text.style.StrikethroughSpan
import android.text.style.StyleSpan
import android.text.style.SubscriptSpan
import android.text.style.SuperscriptSpan
import android.text.style.TypefaceSpan
import android.text.style.URLSpan
import android.text.style.UnderlineSpan
import android.widget.TextView
import androidx.compose.foundation.text.ClickableText
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.TextLayoutResult
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.TextUnit
import androidx.compose.ui.unit.sp
import androidx.compose.ui.unit.takeOrElse
import androidx.core.text.HtmlCompat

private const val URL_TAG = "url_tag"
private val LIST_REGEX = "(<li\\s*[^>]*>)(.*)(</li>)".toRegex()

@Composable
internal fun HtmlText(
text: String,
modifier: Modifier = Modifier,
style: TextStyle = TextStyle.Default,
softWrap: Boolean = true,
overflow: TextOverflow = TextOverflow.Clip,
maxLines: Int = Int.MAX_VALUE,
onTextLayout: (TextLayoutResult) -> Unit = {},
linkClicked: ((String) -> Unit)? = null,
flags: Int = HtmlCompat.FROM_HTML_MODE_COMPACT,
urlSpanStyle: SpanStyle = SpanStyle(
color = linkTextColor(),
textDecoration = TextDecoration.Underline,
),
) {
val fontSize = style.fontSize.takeOrElse { 12.sp }
val content = text.asHTML(fontSize, flags, urlSpanStyle)
if (linkClicked != null) {
ClickableText(
modifier = modifier,
text = content,
style = style,
softWrap = softWrap,
overflow = overflow,
maxLines = maxLines,
onTextLayout = onTextLayout,
onClick = {
content
.getStringAnnotations(URL_TAG, it, it)
.firstOrNull()
?.let { stringAnnotation -> linkClicked(stringAnnotation.item) }
},
)
} else {
Text(
modifier = modifier,
text = content,
style = style,
softWrap = softWrap,
overflow = overflow,
maxLines = maxLines,
onTextLayout = onTextLayout,
)
}
}

@Composable
internal fun linkTextColor() = Color(
TextView(LocalContext.current).linkTextColors.defaultColor,
)

private fun String.addBullets() =
replace(LIST_REGEX) { matchResult ->
val (startTag, inside, endTag) = matchResult.destructured
"$startTag&nbsp;&nbsp;&nbsp;&nbsp;• $inside$endTag"
}

@Composable
private fun String.asHTML(
fontSize: TextUnit,
flags: Int,
urlSpanStyle: SpanStyle,
) = buildAnnotatedString {
val modifiedHtml = addBullets()
val spanned = HtmlCompat.fromHtml(modifiedHtml, flags)
val spans = spanned.getSpans(0, spanned.length, Any::class.java)

append(spanned.toString())

spans
.filter { it !is BulletSpan }
.forEach { span ->
val start = spanned.getSpanStart(span)
val end = spanned.getSpanEnd(span)
when (span) {
is RelativeSizeSpan -> span.spanStyle(fontSize)
is StyleSpan -> span.spanStyle()
is UnderlineSpan -> span.spanStyle()
is ForegroundColorSpan -> span.spanStyle()
is TypefaceSpan -> span.spanStyle()
is StrikethroughSpan -> span.spanStyle()
is SuperscriptSpan -> span.spanStyle()
is SubscriptSpan -> span.spanStyle()

is URLSpan -> {
addStringAnnotation(
tag = URL_TAG,
annotation = span.url,
start = start,
end = end,
)
urlSpanStyle
}

else -> null
}?.let { spanStyle ->
addStyle(spanStyle, start, end)
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
/*
* Copyright 2023 compose-html
* https://github.com/viluahealthcare/compose-html
*
* Modified for Trikot
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mirego.trikot.viewmodels.declarative.compose.viewmodel.internal.html

import android.graphics.Typeface
import android.text.style.RelativeSizeSpan
import android.text.style.StyleSpan
import android.text.style.SubscriptSpan
import android.text.style.SuperscriptSpan
import android.text.style.TypefaceSpan
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.BaselineShift
import androidx.compose.ui.unit.TextUnit
import androidx.compose.ui.unit.sp
import java.io.File

private const val PATH_SYSTEM_FONTS_FILE = "/system/etc/fonts.xml"
private const val PATH_SYSTEM_FONTS_DIR = "/system/fonts/"

internal fun RelativeSizeSpan.spanStyle(fontSize: TextUnit): SpanStyle =
SpanStyle(fontSize = (fontSize.value * sizeChange).sp)

internal fun StyleSpan.spanStyle(): SpanStyle? = when (style) {
Typeface.BOLD -> SpanStyle(fontWeight = FontWeight.Bold)
Typeface.ITALIC -> SpanStyle(fontStyle = FontStyle.Italic)
Typeface.BOLD_ITALIC -> SpanStyle(
fontWeight = FontWeight.Bold,
fontStyle = FontStyle.Italic,
)
else -> null
}

internal fun SubscriptSpan.spanStyle(): SpanStyle =
SpanStyle(baselineShift = BaselineShift.Subscript)

internal fun SuperscriptSpan.spanStyle(): SpanStyle =
SpanStyle(baselineShift = BaselineShift.Superscript)

internal fun TypefaceSpan.spanStyle(): SpanStyle? {
val xmlContent = File(PATH_SYSTEM_FONTS_FILE).readText()
return if (xmlContent.contains("""<family name="$family""")) {
val familyChunkXml = xmlContent.substringAfter("""<family name="$family""")
.substringBefore("""</family>""")
val fontName = familyChunkXml.substringAfter("""<font weight="400" style="normal">""")
.substringBefore("</font>")
SpanStyle(fontFamily = FontFamily(Typeface.createFromFile("$PATH_SYSTEM_FONTS_DIR$fontName")))
} else {
null
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package com.mirego.sample.ui.showcase.components.text
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.widget.Toast
import androidx.activity.compose.setContent
import com.mirego.sample.viewmodels.showcase.components.text.TextShowcaseNavigationDelegate
import com.mirego.sample.viewmodels.showcase.components.text.TextShowcaseViewModel
Expand All @@ -22,6 +23,10 @@ class TextShowcaseActivity : ViewModelActivity<TextShowcaseViewModelController,
}
}

override fun showMessage(text: String) {
Toast.makeText(this, text, Toast.LENGTH_SHORT).show()
}

override fun close() {
finish()
}
Expand Down
Loading

0 comments on commit ef0983d

Please sign in to comment.