Giter Club home page Giter Club logo

attributedtext's Introduction

AttributedText

AttributedText is a view for displaying some HTML-tagged text using SwiftUI Text View.

A simple example of usage.

Code example:

AttributedText("A unit of <i>length</i> equal to <b>one hundred-millionth of a centimetre</b>, 10<sup>−10</sup> metre, used mainly to express <u>wavelengths and interatomic distances</u>.")

Result:

Example

Features

You can clone the repo and run the AttributedTextExample project to explore the AttributedText features.

These are the main points to pay attention to.

  1. You can define the tags you need or use the defaults.

    You need to set the required tags and provide associated closures. Each closure must be a modifier that is applied to the SwiftUI Text View when a specific tag is encountered.

    Override the default values, for example at application launch.
    @main
    struct ExampleApp: App {
        init() {
            AttributedText.tags = [
                "b": { $0.bold() },
                "i": { $0.italic() }
            ]
        }
    }

    In this case only <b> and <i> tags will be processed. All other tags will be ignored or deleted.

    Set the custom values for each instance.
    private let tags: Dictionary<String, (Text) -> (Text)> = [
        // Set the necessary values.
    ]
    
    var body: some View {
        AttributedText("Text", tags: tags)
    }
  2. Basic modifiers can still be applied, such as changing the font and color of the text.

    Code example:

    AttributedText("This is <b>bold</b> and <i>italic</i> text.")
        .foregroundColor(.blue)
        .font(.title)

    Result:

    1 feature

  3. Handles unopened/unclosed tags.

    Code example:

    AttributedText("This is italic</i> and <b>bold text.")

    Result:

    2 feature

  4. Supports overlapping tags.

    Code example:

    AttributedText("This is <b>bold only, <i>bold and italic</b> and italic only</i> text.")

    Result:

    3 feature

  5. Deletes tags that have no modifiers.

    Code example:

    AttributedText("<unknown>This is <b>bold</b> and <i>italic</i> text.</unknown>")

    Result:

    4 feature

  6. Does not handle HTML characters such as &amp;.

    Code example:

    AttributedText("This is <b>bold</b> &amp; <i>italic</i> text.")

    Result:

    5 feature

  7. Only single-word tags are supported. Tags with more than one word or containing any characters besides letters or numbers are ignored and not removed.

    Code example:

    AttributedText("This is <tag attribute1=\"value1\"> <b>bold</b> and <i>italic</i> text</tag>.")

    Result:

    6 feature

Installation and usage

Via Swift Package Manager

  1. In Xcode 11 or greater select File ▸ Swift Packages ▸ Add Package Dependency.
  2. Paste the link to this repo https://github.com/Iaenhaall/AttributedText.git and click Next.
  3. Define the package options for this package or select the default. Click Next.
  4. Xcode downloads the code from GitHub and adds the package to the your project target. Click Finish.

Manually

  1. Add AttributedText.swift and HTML2TextParser.swift files to your project.

attributedtext's People

Contributors

iaenhaall 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

Watchers

 avatar  avatar  avatar  avatar

attributedtext's Issues

Interesting bug due to Swift's set indeterminism

TL;DR: it seems that Swift's set is causing a glitch in this library in HTML2TextParser.

Problem

Sometimes the italics effect is not applied to the following text:
<b><u><i>bolded underlined and italized</i></u></b>, normal text.

Reproduction code:

struct ContentView: View {
  var body: some View {
    List {
      ForEach(1..<100) { _ in
        AttributedText("<b><u><i>bolded underlined and italized</i></u></b>, normal text")
          .font(.system(size: 20))
      }
    }
  }
}

Result:

Every time the app is launched, different rows will have the glitch above.

Investigation

Initially, I thought it was a SwiftUI issue, however, this code works fine:

struct ContentView: View {
  var body: some View {
    List {
      ForEach(1..<100) { _ in
        Group {
          Text("bolded underlined and italized")
            .bold().italic().underline() // any sorting of this works fine in my tests.
          +
          Text(", normal text")
        }
        .font(.system(size: 20))
      }
    }
  }
}

After digging into the library code, I noticed that in HTML2TextParser's addChunkOfText(_:) the following code is executed:

for tag in tags {
if let action = availableTags[tag] {
textChunk = action(textChunk)
}
}

...where tags is a Set<String>.

Because Swift sets are unordered, every time the for tag in tags code is run, a new sequence of tags is produced and different parses of the same text (like the one above) will produce a different output.

In fact, if we replace the code for tag in tags with for tag in tags.sorted(), for every parse of the same text the same output will be produced. This is great, we've reached determinism. Except, now the glitch above is always present:

The fix was to use another sorting order, this one works for this case: for tag in tags.sorted(by: >):

I'm not sure why having different tags orders cause the issue, if you have any idea, please let me know!

Thank you

Support the recognition of phone numbers, emails, urls and more?

It is an interesting component.
Does it support the recognition of phone numbers, emails and urls that may be in the text?
If it recognizes them will it activate the phone for a phone number, open the mail application for an email and launch Safari Mobile for a web address?
Can we add one or more regex to customize the text and associate an action if the user clicks on it?

Adding more featrures such as Paragraph, Numbering, Lists

Hello!

Really love the library so far.
Is there any plan to add more features such as Paragraph, numbering, lists?

For example:

1

<p> paragraph </p> will be:

paragraph

2

<ul>
  <li>Coffee</li>
  <li>Tea</li>
  <li>Milk</li>
</ul>  

will become:

  • Coffee
  • Tea
  • Milk

3

<ol>
  <li>Coffee</li>
  <li>Tea</li>
  <li>Milk</li>
</ol> 

will become:

  1. Coffee
  2. Tea
  3. Milk

Supporting AsyncImage

Hi there, thanks for the library

Would it be possiable to somehow support img tags to render the image in the src itself? using something like AsyncImage(url: srcFromImage)

 private let tags: Dictionary<String, (Text) -> (Text)> = [
   "img": { _ in Text("\(Image("\(srcTagInaccessible)"))") }
]

Thanks again.

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.