Code Monkey home page Code Monkey logo

htmlconvertercompose's Introduction

HTML Converter for Compose Multiplatform

This library provides a simple API to convert HTML to Compose's AnnotatedString, including styling and paragraphs. It can also be used to convert HTML to unstyled text.

It can be considered as a multiplatform replacement for Android's Html.fromHtml() API with support for more tags and better performance.

Platform Supported
Android
Desktop (JVM)
iOS
Web

The iOS platform is not yet supported: testers and contributors are welcome.

The Web platform should use the DOM wrapper API to insert HTML directly in the web page.

Download

Maven Central

Add the dependency to your module's build.gradle or build.gradle.kts file:

dependencies {
    implementation("be.digitalia.compose.htmlconverter:htmlconverter:0.9.5")
}

For Kotlin Multiplatform projects:

sourceSets {
    val commonMain by getting {
        dependencies {
            implementation("be.digitalia.compose.htmlconverter:htmlconverter:0.9.5")
        }
    }
}

Usage

To display styled HTML in a Text composable:

Text(
    text = remember(html) { htmlToAnnotatedString(html) },
    modifier = Modifier.fillMaxWidth()
)

If called from inside a @Composable function, in most cases it is recommended to use remember() to cache the result of the conversion, to avoid recomputation on each recomposition.

To convert HTML to unstyled text:

val rawText = htmlToString(html)

Both functions take an optional compactMode boolean argument. When set to true, all paragraphs will be separated by a single line break instead of two, as it is normally the case for the tags: p, blockquote, pre, ul, ol, dl, h1, h2, h3, h4, h5, h6. The default value is false.

Custom styling

The htmlToAnnotatedString() function takes an optional style argument of type HtmlStyle which allows to customize styling. The currently provided options are:

  • linkSpanStyle: Optional style for hyperlinks (content of a tags). Default is a simple underline. When set to null, hyperlinks will not be styled, which can be useful in case they are not clickable (see next section).
  • indentUnit: Unit of indentation for block quotations and nested lists. Default is 24 sp. Note that em units are not yet supported for indentation in Compose Desktop.

For example, here is how to style hyperlinks to use the theme's primary color with no underline:

val linkColor = MaterialTheme.colors.primary
val convertedText = remember(html, linkColor) {
    htmlToAnnotatedString(
        html,
        style = HtmlStyle(linkSpanStyle = SpanStyle(color = linkColor))
    )
}
Text(
    text = convertedText,
    modifier = Modifier.fillMaxWidth()
)

Handling hyperlink clicks

Hyperlinks (content of a tags) will be annotated with the experimental UrlAnnotation. It is required to add custom code to detect clicks on these annotations and handle the navigation action accordingly.

For example, the ClickableText composable can be used, even if that solution is not perfect because it captures all touch events:

val convertedText = remember(html) { htmlToAnnotatedString(html) }
ClickableText(
    text = convertedText,
    modifier = Modifier.fillMaxWidth(),
    onClick = { position ->
        convertedText
            .getUrlAnnotations(position, position)
            .firstOrNull()?.let { range -> onLinkClick(range.item.url) }
    }
)

Custom parsing

The htmlToAnnotatedString() and htmlToString() functions provide an overload that accepts an HTMLParser first argument in place of a String.

HTMLParser is an interface that you may implement to provide your own parser, in case the HTML is not directly available as a String (for example as a character stream or encoded using a binary format).

The default implementation uses the KtXml multiplatform XML parser library combined with extra code to handle HTML entities and invalid HTML.

Supported HTML tags

  • Inline tags with styling: strong, b (bold), em, cite, dfn, i (italic), big (bigger text), small (smaller text), tt, code (monospace font), a (hyperlink), u (underline), del, s, strike (strikethrough), sup (supertext), sub (subtext)
  • Block tags (paragraphs): p, blockquote, pre (including monospace font), div, header, footer, main, nav, aside, section, article, address, figure, figcaption, video, audio (no player shown, only inline text)
  • Horizontal rule: hr (no line drawn, but marks a new paragraph)
  • Lists: ul, ol, li, dl, dt, dd
  • Section headings: h1, h2, h3, h4, h5, h6
  • Line break: br

The following tags are skipped, along with their content: script, head, table, form, fieldset.

Others tags are ignored and replaced by their content, if any.

All HTML entities appearing in the text will be properly decoded as well.

Used libraries

What to expect from future versions

  • Unit tests
  • Better clickable hyperlinks support
  • Support for displaying images as inline content
  • iOS support (with help from the community).

License

Copyright (C) 2023 Christophe Beyls
 
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.

htmlconvertercompose's People

Contributors

cbeyls avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

htmlconvertercompose's Issues

Support determining the style of hyperlinks

Right now hyperlinks are always underlined and it would be nice if it was possible for clients to define the SpanStyle used there.

I understand this goes beyond the scope of replacing Android's Html.fromHtml() API, so I totally understand if it’s also out of the scope of this library. But since this may potentially be a blocker for some people (it would be for me), I thought I would still file this just in case.

I guess the simplest option would be to receive a urlSpanStyle as an argument for AnnotatedStringHtmlHandler. I’m hoping since we’re already receiving the compactMode boolean there, this won’t hurt the API too much.

I’ll open a PR so it hopefully helps discussing about this change. And thanks a lot for open sourcing this ❤️

Support <br> (instead of only <br/>)

I’m not a line break tag expert and I don’t have any authority over the topic, but it seems that just <br> is a pretty popular and well accepted form of using the line break tag. I actually thought this was a bug in the library since my line breaks weren’t working, but then I realized it explicitly doesn’t do anything on the line break tag open. I thought the fix would be to simply do the same thing we do on tag close, but it seems there’s more to it.

This is what the sample looks like right now, with a red box at the bottom so we can observe the bottom space of the text:

sample

If I simply change the <br /> to a <br> in the sample, this is what we get:

sample2

We lost the line break as expected, but for some reason now we have a line break at the end of the text. So if I proceed with the fix I had in mind, this is what I get:

sample3

Line break is back but 1. it’s just a single line break now for some reason, and 2. the mysterious line break in the end remains. I haven’t investigated it further and I thought I’d file the issue just in case this is already something known.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.