Cocoanetics / DTCoreText

Methods to allow using HTML code with CoreText
BSD 2-Clause "Simplified" License
6.34k stars 1.18k forks source link

Empty anchor element support #1264

Closed hehonghui closed 1 year ago

hehonghui commented 1 year ago

Hi, Cocoanetics team, thank you for this awesome project.

I have a problem, in some html pages there are some empty a tags without content for anchor positioning, when the user clicks this anchor point can jump to the location of this anchor point. But now DTCoreText seems to ignore this kind of anchor tags without content, if I want to implement the empty anchor tag positioning function, how should I do it?

Thank you!

Similar to the code below, click a button to position an empty anchor at anchor_123's location. The code corresponding to DTCoreText is similar to rangeOfAnchorNamed, scrollToAnchorNamed

<!DOCTYPE html>
<html>

<head>
    <style type="text/css">
    p.sentence_1 {
        height: 100vh;
        background-color: gray;
    }

    p.sentence_2 {
        height: 50vh;
        background-color: green;
    }
    </style>
</head>

<body>
    <button onclick="document.getElementById('anchor_123').scrollIntoView();">Go to chapter 2</button>
    <p class="sentence_1" height="1024vh;">typographic character units, word separators, letter-spacing or word-spacing...</p>

<!-- this is a empty anchor tag,  we can use document.getElementById("anchor_123").scrollIntoView(); scroll to the anchor_123 tag -->
    <a id="anchor_123" name="anchor_123"></a>
    <h2>Chapter 2</h2>
    <p class="sentence_2">bring your lips tightly together, especially to show disapproval or worry</p>
</body>

</html>
hehonghui commented 1 year ago

@odrobnik any suggestion for this ?

odrobnik commented 1 year ago

I would insert an invisible character and give it an attribute, probably a link attribute with only with the #anchor. This can then be found when you want to scroll to it.

hehonghui commented 1 year ago

I would insert an invisible character and give it an attribute, probably a link attribute with only with the #anchor. This can then be found when you want to scroll to it.

If we insert a invisible character, the attributed string will be changed. I found anthor way to do that, if parse a tag which has anchor id and it's content is empty, i store the id and text range location into a dictionay. When i need the anchor, i take it from the dictionary.

odrobnik commented 1 year ago

but where do you put the dictionary? In an attributed string an attribute cannot have an empty range, it has to have at least one character. So I would probably add the anchor on the next non-empty range following.

hehonghui commented 1 year ago

I create a dictionary property in html builder. This sulotuon works for me. "add the anchor on the next non-empty range following." That's a better way to do this. 🍺