Git Product home page Git Product logo

swiftrichstring's Issues

Shortcut for MarkupString parser

Add a new func to String instances which allows you to parse a tagged (html-like) string and return the NSMutableAttributed string.

It will be called renderTags(withStyles:).

Follows an example:

let sourceTaggedString = "<center>The quick brown fox</center>\njumps over the lazy dog is an <italic>English-language</italic> pangram—a phrase that contains <italic>all</italic> of the letters of the alphabet. It is <extreme><underline>commonly</underline></extreme> used for touch-typing practice."
let _ = sourceTaggedString.renderTags(withStyles: [tag_center,tag_italic,tag_extreme,tag_underline])

Build failed with version 2.0.5 / XCode 9.4 / iOS 11.4

Build failed with latest version 2.0.5 and XCode 9.4 / iOS 11.4
(deployment target iOS 9.1)

Pods/SwiftRichString/Sources/SwiftRichString/Attributes/CommonsAttributes.swift:57:53: 'SymbolicTraits' is not a member type of 'UIFontDescriptor'

Text/Icons disappear when Stroke attribute is applied

@malcommac
Every time I apply Stroke attribute to text any font-icon, it just disappears. Why?

static let nameTitle = Style({
        $0.color = .white
        $0.stroke = StrokeAttribute(color: .black, width: 0.1)
        $0.font = FontAttribute(font: .pageTitle)
        $0.shadow = ShadowAttribute(color: UIColor.black.withAlphaComponent(0.2), radius: 2.0, offset: CGSize(width: 1, height: 1))
    })

Touch feature

Hi, your lib is great 👍
Do you have a plan to add handle touch feature to tag?

Fixed missing font attributes while rendering StyleGroup

Hi,
I've just updated from 2.0.1 to 2.0.2, and all my styles are gone


Before:
img_0064
After:
img_0065

            let baseFontSize: CGFloat = 16
            
            let headerStyle = Style {
                $0.font = UIFont.boldSystemFont(ofSize: self.baseFontSize * 1.15)
                $0.lineSpacing = 1
                $0.kerning = Kerning.adobe(-20)
            }
            let boldStyle = Style {
                $0.font = UIFont.boldSystemFont(ofSize: self.baseFontSize)
            }
            let italicStyle = Style {
                $0.font = UIFont.italicSystemFont(ofSize: self.baseFontSize)
            }

            let style = StyleGroup(base: Style {
                $0.font = UIFont.systemFont(ofSize: self.baseFontSize)
                $0.lineSpacing = 2
                $0.kerning = Kerning.adobe(-15)
                }, [
                    "h3": headerStyle,
                    "h4": headerStyle,
                    "h5": headerStyle,
                    "strong": boldStyle,
                    "b": boldStyle,
                    "em": italicStyle,
                    "i": italicStyle,
                    "li": Style {
                        $0.paragraphSpacingBefore = self.baseFontSize / 2
                        $0.firstLineHeadIndent = self.baseFontSize
                        $0.headIndent = self.baseFontSize * 1.71
                    },
                    "sup": Style {
                        $0.font = UIFont.systemFont(ofSize: self.baseFontSize / 1.2)
                        $0.baselineOffset = Float(self.baseFontSize) / 3.5
                    }])
            
            attrString = bodyHTML.set(style: style)

Original text is:

<strong>Parler du don d'organe n'est plus tabou. Je me renseigne, j'en discute avec mes proches,... et je décide!</strong>  

En Belgique, au dĂ©but des annĂ©es 2000, le nombre de donneurs d’organes avait tendance Ă  diminuer et les listes d’attente Ă  augmenter considĂ©rablement ayant comme corollaire une augmentation de la mortalitĂ© des patients inscrits sur les listes d’attente. 

Soucieux de cette situation, en juin 2005, le Ministre en charge de la SantĂ© publique a souhaitĂ© mettre sur pied une vaste campagne de sensibilisation entiĂšrement dĂ©diĂ©e au don d’organes. 

Depuis, de nombreuses actions entreprises par le SPF Santé publique viennent renforcer toutes celles qui sont accomplies au quotidien par les coordinateurs de transplantation, les coordinateurs locaux de don, les associations de familles de donneurs, les associations de patients transplantés et ce, depuis de trÚs nombreuses années. 

<strong>Objectifs poursuivis</strong> 

Les objectifs principaux de cette campagne sont: 
<li style="text-align: justify;">‱ d’amĂ©liorer la sensibilisation au don auprĂšs des diffĂ©rents groupes auxquels les messages s’adressent,</li>
<li style="text-align: justify;">‱ d’inviter les citoyens Ă  «oser» en parler en famille, entre amis, entre collĂšgues. Aborder la mort – sa propre mort – reste relativement tabou pour beaucoup.</li> 

<strong>Pour en savoir plus... <a href="http://www.health.belgium.be/fr/sante/prenez-soin-de-vous/debut-et-fin-de-vie/don-dorganes" target="_blank">www.health.belgium.be/fr/sante/prenez-soin-de-vous/debut-et-fin-de-vie/don-dorganes</a></strong>

Fixed internal parser

When I apply tags to a very large text, the attributes start getting applied to strange locations in text. I tried playing with this but haven't yet detected a pattern.

Question: Is there a size limit for the text being tagged?

Remove throws in MarkupString

Remove throws in MarkupString in favour of nil results when parsing fails.
It will remove lots of boilerplate code.

When applying StokeAttribute color becomes transparent

Using following code:

let titleStyle = Style("title", {
            $0.font = FontAttribute(font: .WorkSansExtraBold(17))
            $0.align = .center
            $0.color = UIColor.white
            $0.stroke = StrokeAttribute(color: UIColor.black, width: 1)
            $0.kern = 2
        })

And text color becomes transparent. Any ideas why ?

Thanks !

Dynamic value support for TagAttributes (ie. apply link value from an 'a'/'href' tag)

When trying to convert HTML to attributedText with this wonderful tool, the only thing I'm missing is a way to construct the linkURL with the content of a tag attribute.

I've looked into your code and here's an idea: instead of taking an optional URL for the Style linkURL property, what about a "URLConvertible" type?

Here's a draft of what it could look like, but I don't understand your parsing process (yet) to be able to fully implement it.

//MARK: - URLConvertible

/// An enumeration representing the source of the URL to be applied.
///
/// - url: URL type.
/// - string: String url.
/// - tagAttribute: value of attribute from a parsed tag (ie: "href").
/// - tagText: text content from a parsed tag.
public enum URLConvertible {
    case url(URL)
    case string(String)
    case tagAttribute(String)
    case tagText
    
    func url(for tag: StyleGroup.TagAttribute?) -> URL? {
        switch self {
        case .url(let url):
            return url
        case .string(let string):
            return URL(string: string)
        case .tagAttribute(let attribute):
            return URL(string: tag.attributes[attribute])
        case .tagText:
            return URL(string: tag.content)
        }
    }
    
}

We could then just do the following:

attrString.add(style: StyleGroup(["a" : Style {
    $0.linkURL = .tagAttribute("href")
}]))

Compatibility issue with NightNight library

Hi,

I always had this very simple style with a simple string, and the alignment always worked. Now after upgrading to 2.10 the alignment does not work anymore?

let smaller = Style {
  $0.font = Global.Font.RegularFont12
  $0.alignment = .center
}

EDIT: I downgraded to 2.0.5, now it works again.

Thanks!

Possible to go from NSAttributedString, to "simple" tags?

In this great library, it's unclear:

Say I have an attributed string, which has (let's say) ONLY bold and italic sections.

I want to PRODUCE THIS OUTPUT:

This string <b>has</b> only some <i>bold and some</i> italic.

As you know, you can certainly generate html using Apple's built-in generator, but it produces wildly complex CSS output (see below for example).

So, I know that with SwiftRichString you can go FROM something like

This string <b>has</b> only some <i>bold and some</i> italic.

to an NSAttributedString - but can you go in the other direction???

Sorry it's a bit unclear from the doco - or maybe I'm just lame :)

Example of Apple's crappy full-css output...,

if you use .attributedText.data

><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="Content-Style-Type" content="text/css">
<title></title>
<meta name="Generator" content="Cocoa HTML Writer">
<style type="text/css">
p.p1 {margin: 0.0px 0.0px 0.0px 0.0px; font: 14.0px 'Open Sans'}
span.s1 {font-family: 'Open Sans'; font-weight: normal; font-style: normal; font-size: 14.00pt}
span.s2 {font-family: 'OpenSans-SemiboldItalic'; font-weight: bold; font-style: italic; font-size: 14.00pt}
</style>
</head>
<body>
<p class="p1"><span class="s1">So, </span><span class="s2">Apple made</span><span class="s1"> this stuff OK</span></p>
</body>
</html>
<

MarkupString removed?

I'm converting to version 2 of this library and I just wanted to make sure you removed MarkupString ? What's the recommend upgrade path in that case?

Link rendering

Feature request for URL/link rendering similar to <a> in HTML

Type of expression is ambiguous without more context

I'm trying to init using the following code:

let bold = Style("bold", {
                $0.font = .bold(size: 16)
                $0.color = .black
})

Using Xcode 10/Swift 4.2 I get the following error:

Type of expression is ambiguous without more context

Render HTML text

Hello, Thank you for this cool framework!. I just need to display an HTML code using this. But when I run the app, my label shows nothing!.

here is my code:

 let file = Bundle.main.path(forResource: "html", ofType: "txt")!
        do {
            htmlBody = try String(contentsOfFile: file, encoding: .utf8)
        } catch let error {
            print(error)
        }

        label.attributedText = htmlBody.set(style: "str")

my txt file has all tags and styles so I don't need it to create style group.
How can I fix this?

Malloc issue leads to crash for a mixed Swift version implementation

I have discovered a crash scenario in the following situation:

  • Release Configuration
  • Project compiled with Swift 3.2
  • SwiftRichString compiled with Swift 4.0 (using SwiftRichString version 1.0.1)
  • macOS project (could also be present in iOS - not tested)
  • macOS Sierra version 10.12.6
  • Xcode version 9.2

I have created a simple macOS project that reliably reproduces the issue:
https://github.com/scottcarter/SwiftRichString_MallocBug

I found that if any of the first three criteria is changed, the problem goes away. I.e. if a Debug configuration is used, if the project is compiled with Swift 4.0, or I compile SwiftRichString with Swift 3.2 (using SwiftRichString version 0.9.10).

Style for plain strings?

Is there a way to automatically continue the current style when concatenating/appending strings to attributed strings? I'm using set with each string now, but I'm about to move into multiple styles.
Alternatively, a way to set a style based on the style of the final character of an attributed string could also work.

The attributes field not returning everything

I have this style:

let inputStyle = Style {
        $0.font = UIFont.bsFont(type: .medium, size: 13)
        $0.color = UIColor.white
        $0.kerning = Kerning.point(0.2)
}

On V2.0.1 inputStyle.attributes returns 3 atrributes.
On V2.0.5 inputStyle.attributes returns 1 atrributes.

SwiftRichString 2.x for Swift 3.x

After upgrading Xcode to version 9.3 I can't longer build the project.

<unknown>:0: error: fatal error encountered while reading from module 'SwiftRichString'; please file a bug report with your project and the crash log
<unknown>:0: note: compiling as Swift 3.3, with 'SwiftRichString' built as Swift 4.1 (this is supported but may expose additional compiler issues)
Cross-reference to module 'Foundation'
... NSAttributedStringKey

0  swift                    0x0000000107da8ffa PrintStackTraceSignalHandler(void*) + 42
1  swift                    0x0000000107da83b6 SignalHandler(int) + 966
2  libsystem_platform.dylib 0x00007fff5e65ff5a _sigtramp + 26
3  libsystem_platform.dylib 000000000000000000 _sigtramp + 2711224512
4  libsystem_c.dylib        0x00007fff5e48a312 abort + 127
5  swift                    0x00000001054d6bae swift::ModuleFile::fatal(llvm::Error) + 2062
6  swift                    0x00000001054e8f9a swift::ModuleFile::getTypeChecked(llvm::PointerEmbeddedInt<unsigned int, 31>) + 13418
7  swift                    0x00000001054f7e17 swift::SILDeserializer::readSILFunction(llvm::PointerEmbeddedInt<unsigned int, 31>, swift::SILFunction*, llvm::StringRef, bool, bool) + 455
8  swift                    0x000000010550b00c swift::SILDeserializer::getFuncForReference(llvm::StringRef) + 748
9  swift                    0x000000010550c4cd swift::SILDeserializer::readVTable(llvm::PointerEmbeddedInt<unsigned int, 31>) + 605
10 swift                    0x000000010520076b swift::SILLinkerVisitor::processClassDecl(swift::ClassDecl const*) + 91
11 swift                    0x00000001052473c5 swift::SILModule::lookUpVTable(swift::ClassDecl const*) + 261
12 swift                    0x000000010520038f swift::SILLinkerVisitor::linkInVTable(swift::ClassDecl*) + 31
13 swift                    0x00000001051ffe45 swift::SILLinkerVisitor::process() + 517
14 swift                    0x00000001051ffb6f swift::SILLinkerVisitor::processFunction(swift::SILFunction*) + 79
15 swift                    0x0000000105246555 swift::SILModule::linkFunction(swift::SILFunction*, swift::SILOptions::LinkingMode) + 117
16 swift                    0x0000000104f843c9 runOnFunctionRecursively(swift::SILFunction*, swift::FullApplySite, swift::SILOptions::LinkingMode, llvm::DenseSet<swift::SILFunction*, llvm::DenseMapInfo<swift::SILFunction*> >&, llvm::ImmutableSet<swift::SILFunction*, llvm::ImutContainerInfo<swift::SILFunction*> >::Factory&, llvm::ImmutableSet<swift::SILFunction*, llvm::ImutContainerInfo<swift::SILFunction*> >, swift::ClassHierarchyAnalysis*) + 4249
17 swift                    0x0000000104f82e56 (anonymous namespace)::MandatoryInlining::run() + 342
18 swift                    0x0000000104f04db9 swift::SILPassManager::runOneIteration() + 10217
19 swift                    0x0000000104f081eb swift::runSILDiagnosticPasses(swift::SILModule&) + 2123
20 swift                    0x0000000104407697 performCompile(swift::CompilerInstance&, swift::CompilerInvocation&, llvm::ArrayRef<char const*>, int&, swift::FrontendObserver*, swift::UnifiedStatsReporter*) + 32167
21 swift                    0x00000001043fde64 swift::performFrontend(llvm::ArrayRef<char const*>, char const*, void*, swift::FrontendObserver*) + 7908
22 swift                    0x00000001043b28b5 main + 18917
23 libdyld.dylib            0x00007fff5e3de115 start + 1
24 libdyld.dylib            0x00000000000000a8 start + 2713853844

What about <p> tag for paragraph separation?

Hi,
I would like to have a p tag instead of /n or br for paragraph delimitation.
And of course to be able to define a base style for a paragraph that could be changed automatically in favor of other styles selected.
There's a way to set style priority and to successful process this tag?

Right know it just ignore it

Fixed an issue when rendering emojis and other unicode strings

Some emojist stoped working after update.
this code is the code I have

let messageStyle = Style {
    $0.font = UIFont.systemFont(ofSize: 12)
    $0.kerning = Kerning.point(0.3)
    $0.color = UIColor.bsBase
}
self.messageLabel.attributedText = "😇".set(style: messageStyle)

On version 2.0.1
screen shot 2018-09-12 at 12 12 24

On version 2.0.2+
screen shot 2018-09-12 at 12 06 39

Any clues what may have caused this?

apply defaults to document

It would be nice if there was an easy way to apply defaults to the document. For example: define a document as default right-to-left, define a document with a default font (family, size, etc), define a document with a theme (background color, text color, etc).

All in all, a very nice project. I'm enjoying playing with it.

Fixed an issue with Style copying via `byAdding()` function

Hello.

I would like to report/highlight the breaking changes of the latest versions.

With this simple group declaration

typealias MainFont = Font.HelveticaNeue

enum Font {
    enum HelveticaNeue: String {
        case light = "Light"
        case bold = "Bold"
        case boldItalic = "BoldItalic"
        func with(size: CGFloat) -> UIFont {
            return UIFont(name: "HelveticaNeue-\(rawValue)", size: size)!
        }
    }
}

let normal = Style {
    $0.font = MainFont.light.with(size: 16)
}

let bold = normal.byAdding {
    $0.font = MainFont.bold.with(size: 16)
}

let bold_italic = normal.byAdding {
    $0.font = MainFont.boldItalic.with(size: 15)
}

let stylesDefs = [
    "bold": bold,
    "bold_italic": bold_italic,
]

let defaultStyles = StyleGroup(base: normal, stylesDefs)

And the following text:

var text = "This search engine is specifically designed to solve <bold>crosswords</bold> or <bold>arrowords puzzles</bold>.\n\nIn order to solve a word, you can either enter its <bold>definition</bold> or its <bold>pattern</bold>.\n\n<bold_italic>For patterns, you can simply press the spacebar for each unknown letter.</bold_italic>"
text.set(style: defaultStyles)

The output with version 2.0.1 is as expected:

swiftrichstring-2 0 1

With version 2.0.2 I've this:

swiftrichstring-2 0 2

With version 2.0.3, this:

swiftrichstring-2 0 3

And the latest 2.0.4 is the worst:

swiftrichstring-2 0 4

I've tried to use your new declaration style

let normal = Style {
    $0.font = SystemFonts.HelveticaNeue_Light.font(size: 16)
}

let bold = Style {
    $0.font = SystemFonts.HelveticaNeue_Bold.font(size: 16)
}

let bold_italic = Style {
    $0.font = SystemFonts.HelveticaNeue_BoldItalic.font(size: 15)
}

But it does not solve the issue, I keep getting the output of the last screenshot.

So either it's a breaking change or it's a bug, but for now, I will force the use of version 2.0.1 as it is the only one who gives the expected output.

Fixed font/size attributes which are not inherited correctly

add method will override all existing attributes.

let styleA = Style {
	$0.color = UIColor.white
	$0.size = 24
}

let styleB = Style {
	$0.color = UIColor.white
	$0.size = 14
}

let styleC = Style {
	$0.color = UIColor.red
}

let a = "hello".set(style: styleA)
let b = "world!".set(style: styleB)
let ab = (a + b).add(style: styleC)

the expected result of ab should keep different font size and append red color. But real result is reset font size and append red color.

p.s. version 2.0.1

Line separation with <br> tag keeps ">" after applying render()

Hi,

I was trying to create an attributed string from this:
"<p><b>5 July</b><br>- It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout.<br>- of the printing and typesetting industry. Lorem Ipsum has been the industry's </p>".

with the following code:
let style = Style.default {
$0.font = FontAttribute(.HelveticaNeue_Light, size: 16)
$0.color = ColorPalette.turquoiseBlue
}
let parser = MarkupString(source: news.subtitle, styles: [style])!
let attributedText = parser.render()

The result that I am getting is like this:
"...>- It is a long established..."

Dont know if its a bug or I am doing something wrong.

Compile issue with Xcode 9 Beta

Im getting this error when trying to compile the project using Carthage pointing out to the beta version of Xcode:

*** Building scheme "SwiftRichString" in SwiftRichString.xcworkspace
Build Failed
Task failed with exit code 65:
/usr/bin/xcrun xcodebuild -workspace /Users/jgarcia/Developer/music-mobile-ios-v3/Carthage/Checkouts/SwiftRichString/SwiftRichString.xcworkspace -scheme SwiftRichString -configuration Release -derivedDataPath /Users/jgarcia/Library/Caches/org.carthage.CarthageKit/DerivedData/SwiftRichString/0.9.8 -sdk iphoneos ONLY_ACTIVE_ARCH=NO BITCODE_GENERATION_MODE=bitcode CODE_SIGNING_REQUIRED=NO CODE_SIGN_IDENTITY= CARTHAGE=YES clean build

This usually indicates that project itself failed to compile. Please check the xcodebuild log for more details: /var/folders/5y/6n4_nl4x40qg1z_6n8d_z9xc0000gp/T/carthage-xcodebuild.pNKVla.log

Any suggestion of what should I do.

Thanks.

commented-out example code obsolete?

The file ViewController.swift in the DemoApp folder has the following code in lines 64-66:

//	let sourceURL = URL(fileURLWithPath: "...")
//	let sourceText = RichString(sourceURL, encoding: .utf8, [bold,italic])!
//	let renderedText = sourceText.text

The method RichString() doesn't seem to exist anywhere. Is there a replacement function? Or is it hiding from me?

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.