Giter VIP home page Giter VIP logo

richtext's Introduction

RichText

Swift: 5.1+ iOS: 13.0+ macOS-10.15+

github

스크린샷 2021-08-28 오전 12 14 09 스크린샷 2021-08-28 오전 12 13 59
LightMode DarkMode

Code

import SwiftUI
import RichText

struct RichText_Test: View {
    @State var  html = ""
    
    var body: some View {
       ScrollView{
            RichText(html: html)
                .lineHeight(170)
                .colorScheme(.auto)
                .imageRadius(12)
                .fontType(.system)
                .foregroundColor(light: Color.primary, dark: Color.primary)
                .linkColor(light: Color.blue, dark: Color.blue)
                .colorPreference(forceColor: .onlyLinks)
                .linkOpenType(.SFSafariView())
                .customCSS("")
                .placeholder {
                    Text("loading")
                }
                .transition(.easeOut)
        }
    }
}

struct RichText_Test_Previews: PreviewProvider {
    static var previews: some View {
        RichText_Test()
    }
}

Swift Package Manager

The Swift Package Manager is a tool for automating the distribution of Swift code and is integrated into the swift compiler.

Once you have your Swift package set up, adding RichText as a dependency is as easy as adding it to the dependencies value of your Package.swift.

dependencies: [
    .package(url: "https://github.com/NuPlay/RichText.git", .upToNextMajor(from: "2.0.0"))
]

More

import SwiftUI
import RichText

struct RichText_Test: View {
    @State var  html = ""
    
    let config: Configuration = Configuration(customCSS: String, fontType: FontType, fontColor: ColorSet, lineHeight: CGFloat, colorScheme: ColorScheme, imageRadius: CGFloat, linkOpenType: LinkOpenType, linkColor: ColorSet, isColorsImportant: ColorPreference)
    
    var body: some View {
       ScrollView{
        RichText(html: text, configuration: config, placeholder: AnyView?)
                .lineHeight(170)
                .colorScheme(.auto)
                .imageRadius(12)
                .fontType(.system)
                .foregroundColor(light: Color.primary, dark: Color.primary)
                .linkColor(light: Color.blue, dark: Color.blue)
                .colorPreference(forceColor: .onlyLinks)
                .linkOpenType(.SFSafariView())
                .customCSS("")
                .placeholder {
                    Text("loading")
                }
                .transition(.easeOut)
        }
    }
}

struct RichText_Test_Previews: PreviewProvider {
    static var previews: some View {
        RichText_Test()
    }
}

Custom Font

import SwiftUI
import RichText

struct RichText_Test: View {
    @State private var  html = ""
    
    var body: some View {
       ScrollView{
        RichText(html: html)
        .fontType(.customName("Noto Sans"))
        .customCSS("""
                 @font-face {
                        font-family: 'Noto Sans';
                        src: url("NotoSans-Regular.ttf") format('truetype');
                            }
                """)
        }
    }
}

struct RichText_Test_Previews: PreviewProvider {
    static var previews: some View {
        RichText_Test()
    }
}

Sample Text

Click
import SwiftUI
import RichText

struct RichText_Test: View {
    @State var  html = """
        <h1>Non quam nostram quidem, inquit Pomponius iocans;</h1>
        
        <img src = "https://user-images.githubusercontent.com/73557895/126889699-a735f993-2d95-4897-ae40-bcb932dc23cd.png">
        

        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quis istum dolorem timet? Sit sane ista voluptas. Quis est tam dissimile homini. Duo Reges: constructio interrete. <i>Quam illa ardentis amores excitaret sui! Cur tandem?</i> </p>

        <dl>
            <dt><dfn>Avaritiamne minuis?</dfn></dt>
            <dd>Placet igitur tibi, Cato, cum res sumpseris non concessas, ex illis efficere, quod velis?</dd>
            <dt><dfn>Immo videri fortasse.</dfn></dt>
            <dd>Quae qui non vident, nihil umquam magnum ac cognitione dignum amaverunt.</dd>
            <dt><dfn>Si longus, levis.</dfn></dt>
            <dd>Ita ne hoc quidem modo paria peccata sunt.</dd>
        </dl>


        <ol>
            <li>Possumusne ergo in vita summum bonum dicere, cum id ne in cena quidem posse videamur?</li>
            <li>Placet igitur tibi, Cato, cum res sumpseris non concessas, ex illis efficere, quod velis?</li>
            <li>Unum nescio, quo modo possit, si luxuriosus sit, finitas cupiditates habere.</li>
        </ol>


        <blockquote cite="http://loripsum.net">
            Aristoteles, Xenocrates, tota illa familia non dabit, quippe qui valitudinem, vires, divitias, gloriam, multa alia bona esse dicant, laudabilia non dicant.
        </blockquote>


        <p>Scrupulum, inquam, abeunti; Conferam tecum, quam cuique verso rem subicias; Audeo dicere, inquit. Maximus dolor, inquit, brevis est. Nos commodius agimus. </p>

        <ul>
            <li>Cur igitur, inquam, res tam dissimiles eodem nomine appellas?</li>
            <li>Omnia peccata paria dicitis.</li>
        </ul>


        <h2>Laboro autem non sine causa;</h2>

        <p>Itaque contra est, ac dicitis; <code>Illa argumenta propria videamus, cur omnia sint paria peccata.</code> </p>

        <pre>Nunc dicam de voluptate, nihil scilicet novi, ea tamen, quae
        te ipsum probaturum esse confidam.

        Sin est etiam corpus, ista explanatio naturae nempe hoc
        effecerit, ut ea, quae ante explanationem tenebamus,
        relinquamus.
        </pre>



        """
    
    var body: some View {
        ScrollView{
           RichText(html: html)
                .lineHeight(170)
                .colorScheme(.auto)
                .imageRadius(12)
                .fontType(.system)
                .foregroundColor(light: Color.primary, dark: Color.primary)
                .linkColor(light: Color.blue, dark: Color.blue)
                .colorPreference(forceColor: .onlyLinks)
                .customCSS("")
                .linkOpenType(.SFSafariView())
                .placeholder {
                    Text("loading")
                }
                .transition(.easeOut)
        }
    }
}

struct RichText_Test_Previews: PreviewProvider {
    static var previews: some View {
        RichText_Test()
    }
}
    

If use for macOS

macOS Guide - This library uses WebView to display HTML.
  • If it is not displayed normally, please allow "Outgoing Connections (Client)" permission.

How To Use

Variable explanation

  • html : which you want to show (String type)

Modifier

Modifier Default
.foregroundColor(light: Color, dark: Color) (light: "000000", dark: "F2F2F2")
.imageRadius(_ imageRadius: CGFloat) 0
.customCSS(_ customCSS: String) ""
.lineHeight(_ lineHeight: CGFloat) 170
.colorScheme(_ colorScheme: ColorScheme) .auto
.fontType(_ fontType: FontType) .system
.linkColor(_ linkColor: ColorSet) ColorSet(light: "#007AFF", dark: "#0A84FF", isImportant: true)
.linkOpenType(_ linkOpenType: LinkOpenType) .Safari
.placeholder<T>(@ViewBuilder content: () -> T) nil
.colorPreference(forceColor: ColorPreference) .onlyLinks
.transition(_ transition: Animation?) .none
  • foregroundColor (default: (light: "000000", dark: "F2F2F2")) : Color of Text
  • imageRadius (default: 0) : Radius of image corner
  • customCSS(default: ""): You can add CSS if you want
  • lineHeight (default: 170) : Height of each line
  • colorScheme(default: .auto) : light or dark mode (it changes text color)
  • fontType(default: .system): Font type in RichText view
  • linkColor (default: ColorSet(light: "#007AFF", dark: "#0A84FF")) : linkColor (Color or UIColor)
  • linkOpenType (default: .Safari) : When the user clicks the link contained in html, Way to take action
  • placeholder (default: nil) : What to display until Richtext views are completely drawn (View type)
  • transition(default: .none) : Transition between PlaceHolder and Content
  • colorPreference(default: .onlyLinks) : css '!important', It ignores the color in variable 'html'

Known Issues

If you are trying to display very large content, it may not be displayed.

Planned (Future work):

A variety of options. If you need any options, leave them in the issues or discussion.

richtext's People

Contributors

chaoscoder avatar filip-zielinski avatar macbookator avatar mirko-milovanovic-vidiemme avatar nuplay avatar ohmantics avatar sk-chanch avatar studiogaram 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  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  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  avatar  avatar  avatar  avatar  avatar

richtext's Issues

Wrong tag versions for SPM

Right now I cannot add your package using SPM by specifying a version. The tagged versions should be something like 1.6.0 and not 1.6.

Thanks!

Handling combine/state changes?

Hello and thank you for sharing this! It appears to be working really well for the initial render, but from your example in the readme, changes to the @State var html won't be reflected by the webview. It seems like this function updateUIView would need to get implemented yea? I took a quick pass at this, so lmk if this seems reasonable and ill make a PR:

public func updateUIView(_ uiView: WKWebView, context: Context) {
        let htmlStart = """
            <HTML>
            <head>
                <meta name='viewport' content='width=device-width, shrink-to-fit=YES, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no'>
            </head>
            """
        let htmlEnd = "</BODY></HTML>"
        let htmlString = "\(htmlStart)\(css(colorScheme: self.colorScheme))\(html)\(htmlEnd)"
        uiView.loadHTMLString(htmlString, baseURL:  nil)
    }

I guess we might want to factor that bit out of makeUIView and updateUIView

Text does not show in dark mode

RichText works fine in light mode - but I don't see anything in dark mode. Just a blank black screen.

RichText(html: myHtml)
    .placeholder {
        Text("Loading myHtml")
    }

Does not obey frame

Screen Shot 2022-07-20 at 5 14 09 PM

Frame is set to 48 tall.

Message body:
<p>This is a <strong>fancy</strong> <strong><span style=\"color: rgb(226, 80, 65);\">HTML</span></strong> <span style=\"background-color: rgb(97, 189, 109);\">message</span> with some styling.</p><p>And a <a href=\"http://www.google.com\" target=\"_blank\">link to google</a>.</p>

Using linkColor change the links color to the default WebView blue <a> color

If I don't set the .linkColor, the link color uses the RichText default light blue color. But when I try to set my custom color, it does not change to the desired color and fallbacks to the dark blue link color.

RichText(html: htmlString)
        .linkColor(light: Color.white, dark: Color.white)

I am not sure if is related but I am testing this on the latest Xcode 14 beta 5.

macOS support

seems like a very capable library, but can unfortunately not be used for a macOS SwiftUI application due to the lack of UIKit availability.

Horizontal Scroll

Hi, im using the pod, but i have problems when i want to use horizontal scroll and overflows not work when create the css style.

i already support this?

WebView content dynamic height evaluation not working when document changes height

Considering this situation:

struct MyHtmlView: View {
    let longHTML: String = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed est est, mattis vel ante sit amet, porttitor interdum dui. Nunc cursus lobortis ex, ut faucibus felis malesuada id. Vivamus in risus nec dolor ullamcorper tincidunt in at velit. Vestibulum nec mollis ipsum. Phasellus volutpat augue odio, ultricies accumsan magna eleifend tristique. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Pellentesque efficitur sem non dui ultricies sollicitudin eu eu sapien."
    let shortHTML: String = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed est est, mattis vel ante sit amet, porttitor interdum dui. Nunc cursus lobortis ex, ut faucibus felis malesuada id."
    
    @State private var isExpanded: Bool = false
    
    var body: some View {
        VStack {
            RichText(html: isExpanded ? longHTML : shortHTML)
                .lineHeight(120)
                .colorScheme(.auto)
                .transition(.easeOut)
                .background(Color.red)
            
            Button {
                isExpanded.toggle()
            } label: {
                Text("Show more/less")
            }
        }
    }
}

When the HTML changes from a long description to a short one the RichText frame's height remains equal to the bigger one calculated from the long description's height leaving a blank space underneath the RichText view

Question about using custom fonts

I'm trying to get a custom font rendering in my webview.
I feel like I'm doing all the right steps but I'm unable to see a font change.
I tried using the FontType.custom with a name and a UIFont. The UIFont was definitely not nil and was the correct font I wanted passed in. Should using this modifier be the only thing I need? I also tried using custom CSS to change the font. Nothing worked though.
Does someone have an example using a custom font just so I could compare.
For more project context I added this library as a local package because of needing a few small changes to styling. The custom fonts are added to the main target of the project. Do they need to be added as resources to local package?

Thanks for the library - it's very nice

CSS click events

Hi does this support CSS click events? Like can I use a click event to reveal some text? Thanks!

I tried one but it didnt work when I tapped on it.

<DETAILS>...</DETAILS>

I really like this package but I've run into an issue. I've got this code:

import SwiftUI
import RichText
struct MainView : View {
var body: some View { ScrollView { RichText(html: Documents.Welcome) }
}
and when it runs I get a bunch of warnings: [ViewportSizing] maximumViewportInset cannot be larger than frame (similarly for minimumViewportInset). Documents.Welcome is quite large but the warnings didn't seem to be a problem.

But today I added a "details" section:

CLICK HERE

There's a lot of text here.

and nothing renders after the details link. The same document loads in web browsers (Chrome, Safari, etc) perfectly ok.

<Figure> Markup Bug

While it renders

. it is offset from the rest of the text.

Here is the example HTML text:

<figure data-align=\"center\" data-size=\"large\" data-img-src=\"https://www.gamespot.com/a/uploads/original/1596/15969599/4052233-steamskins2.png\" data-ref-id=\"1300-4052233\" data-ratio=\"0.33333333333333\" data-width=\"900\" data-embed-type=\"image\" style=\"width: 900px\"><a class=\"fluid-height\" style=\"padding-bottom:33.3%\" href=\"https://www.gamespot.com/a/uploads/original/1596/15969599/4052233-steamskins2.png\" data-ref-id=\"1300-4052233\"><img alt=\"The days of easily modding your Steam to look the way you want are, sadly, over.\" src=\"https://www.gamespot.com/a/uploads/original/1596/15969599/4052233-steamskins2.png\" srcset=\"https://www.gamespot.com/a/uploads/original/1596/15969599/4052233-steamskins2.png 900w, https://www.gamespot.com/a/uploads/scale_medium/1596/15969599/4052233-steamskins2.png 480w\" sizes=\"(max-width: 900px) 100vw, 900px\" data-width=\"900\"></a><figcaption>The days of easily modding your Steam to look the way you want are, sadly, over.</figcaption></figure>

Here is what is rendered in SwiftUI

CleanShot 2022-10-23 at 14 22 54@2x

Can you advise if there is anything I can do to resolve this or if it is a known bug?

Normal text doesn't show up

Hi, I have the following text:

USDC is a fully collateralized US dollar stablecoin. USDC is the bridge between dollars and trading on cryptocurrency exchanges. The technology behind CENTRE makes it possible to exchange value between people, businesses and financial institutions just like email between mail services and texts between SMS providers. We believe by removing artificial economic borders, we can create a more inclusive global economy.

and it's not showing up:

image

Feature: Additional type to LinkOpenType

Need:

  • Handle clicked url without opening Safari

Possible Solution:

  • Can be added a new type as custom and a parameter as closure which gets URL in order to execute when url selected.

runtime failure: force unwrap

image

This happen on those circumstances where the view will be unallocated before the content was uploaded, there is a crash due to force unwrap of variable height.
Since we don't want to risk an accident, can i suggest to don't force unwrap an optional only to find that it could be void.

LinkOpenType - custom type

Could be my inexperience, but I was hoping to use this new feature in the following way:

  1. I receive HTML content via an api
  2. The HTML contains links that I would like to open within my app, using it to display the content in my UI (not in any browser)
  3. Some of the links from this api come in weird formats like "<a href="/gary-busey/4005-1780/" data-ref-id="4005-1780">Gary Busey"
  4. I was planning to process the link using Regex to rewrite it and load the content in a new view in my app
  5. I tried some simple test code like:
.linkOpenType(.custom({ url in
      print(url)
 }))

but I'm getting the following messages in the Output window after clinking the link:

0x16e1300c0 - [PID=77634] WebProcessProxy::checkURLReceivedFromWebProcess: Received an unexpected URL from the web process
0x1060a9018 - [pageProxyID=14, webPageID=15, PID=77634] WebPageProxy::Ignoring request to load this main resource because it is outside the sandbox

If I click a traditional-looking link like:
<a href="https://api.site.com/gary-busey/4005-15789/\" data-ref-id="4005-15789">Gary Busey
My code will print the URL as expected.

Am I totally off base, trying to use the new feature in this way? If so, what's the intended use of this feature?

Thanks
Maury

FontType doesn't support custom fonts

When I try to set a custom font that I imported into my project it doesn't work

.fontType(.custom(UIFont(name: "NunitoSans-Regular", size: 14.0)))

Custom CSS

Hi, very helpful lib that you have made!
Is it possible to add custom CSS?

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.