From 7bf6785689f8a9b200ea11e6af410a80671fc9c6 Mon Sep 17 00:00:00 2001 From: Tulir Asokan Date: Fri, 15 Apr 2022 23:25:12 +0300 Subject: [PATCH] Linkify links in HTML messages too --- ui/messages/html/parser.go | 24 +++++++++++++++++++++++- ui/messages/textmessage.go | 2 +- 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/ui/messages/html/parser.go b/ui/messages/html/parser.go index d706bf6..e68b7aa 100644 --- a/ui/messages/html/parser.go +++ b/ui/messages/html/parser.go @@ -381,6 +381,7 @@ func (parser *htmlParser) tagNodeToEntity(node *html.Node) Entity { } var spaces = regexp.MustCompile("\\s+") +var links = regexp.MustCompile(`https?://\S+`) func (parser *htmlParser) singleNodeToEntity(node *html.Node) Entity { switch node.Type { @@ -392,7 +393,28 @@ func (parser *htmlParser) singleNodeToEntity(node *html.Node) Entity { if len(node.Data) == 0 { return nil } - return NewTextEntity(node.Data) + indices := links.FindAllStringIndex(node.Data, -1) + if len(indices) == 0 { + return NewTextEntity(node.Data) + } + ent := &ContainerEntity{ + BaseEntity: &BaseEntity{Tag: "span"}, + } + var lastEnd int + for i, item := range indices { + start, end := item[0], item[1] + if start > lastEnd { + ent.Children = append(ent.Children, NewTextEntity(node.Data[lastEnd:start])) + } + link := node.Data[start:end] + linkID := fmt.Sprintf("%s-%d", parser.evt.ID, i) + ent.Children = append(ent.Children, NewTextEntity(link).AdjustStyle(AdjustStyleLink(link, linkID), AdjustStyleReasonNormal)) + lastEnd = end + } + if lastEnd < len(node.Data) { + ent.Children = append(ent.Children, NewTextEntity(node.Data[lastEnd:])) + } + return ent case html.ElementNode: parsed := parser.tagNodeToEntity(node) if parsed != nil && !parsed.IsBlock() && parsed.IsEmpty() { diff --git a/ui/messages/textmessage.go b/ui/messages/textmessage.go index 202452c..a986366 100644 --- a/ui/messages/textmessage.go +++ b/ui/messages/textmessage.go @@ -76,7 +76,7 @@ func (msg *TextMessage) getCache(uiMsg *UIMessage) tstring.TString { link := msg.Text[start:end] linkID := fmt.Sprintf("%s-%d", msg.eventID, i) content = content. - Append(msg.Text[:start]). + Append(msg.Text[lastEnd:start]). AppendTString(tstring.NewStyleTString(link, tcell.StyleDefault.Hyperlink(link, linkID))) lastEnd = end }