Skip to content

Commit

Permalink
fix bad HTML when links overlap
Browse files Browse the repository at this point in the history
  • Loading branch information
dimkr committed Jan 5, 2024
1 parent c764119 commit 3f62e43
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 11 deletions.
28 changes: 17 additions & 11 deletions front/text/plain/convert.go
Original file line number Diff line number Diff line change
Expand Up @@ -117,25 +117,31 @@ func FromHTML(text string) (string, data.OrderedMap[string, string]) {
return strings.TrimRight(res, " \n\r\t"), links
}

func getPlainLinks(text string) map[string]struct{} {
links := map[string]struct{}{}
for _, link := range urlRegex.FindAllString(text, -1) {
links[link] = struct{}{}
}
return links
}

func ToHTML(text string, mentions []ap.Mention) string {
if text == "" {
return ""
}

for link := range getPlainLinks(text) {
text = strings.ReplaceAll(text, link, fmt.Sprintf(`<a href="%s" target="_blank">%s</a>`, link, link))
var b strings.Builder

foundLink := false
for {
loc := urlRegex.FindStringIndex(text)
if loc == nil {
break
}
b.WriteString(text[:loc[0]])
b.WriteString(fmt.Sprintf(`<a href="%s" target="_blank">%s</a>`, text[loc[0]:loc[1]], text[loc[0]:loc[1]]))
text = text[loc[1]:]
foundLink = true
}
if foundLink {
b.WriteString(text)
text = b.String()
}

if len(mentions) > 0 {
var b strings.Builder
b.Reset()
mentions:
for _, mention := range mentions {
if mention.Type != ap.MentionMention {
Expand Down
8 changes: 8 additions & 0 deletions front/text/plain/convert_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -287,6 +287,14 @@ func TestToHTML_Link(t *testing.T) {
assert.Equal(t, expected, html)
}

func TestToHTML_OverlappingLink(t *testing.T) {
post := `this is a plain post with overlapping links: gemini://aa.bb.com/cc gemini://aa.bb.com/cc?dd=ee&ff=gg%20hh`
expected := `<p>this is a plain post with overlapping links: <a href="gemini://aa.bb.com/cc" target="_blank">gemini://aa.bb.com/cc</a> <a href="gemini://aa.bb.com/cc?dd=ee&ff=gg%20hh" target="_blank">gemini://aa.bb.com/cc?dd=ee&ff=gg%20hh</a></p>`

html := ToHTML(post, nil)
assert.Equal(t, expected, html)
}

func TestToHTML_LinkAndLineBreak(t *testing.T) {
post := "this is a plain post with a link: gemini://aa.bb.com/cc?dd=ee&ff=gg%20hh\n... and a line break"
expected := `<p>this is a plain post with a link: <a href="gemini://aa.bb.com/cc?dd=ee&ff=gg%20hh" target="_blank">gemini://aa.bb.com/cc?dd=ee&ff=gg%20hh</a><br/>... and a line break</p>`
Expand Down

0 comments on commit 3f62e43

Please sign in to comment.