references returns an iterator because why not?

This commit is contained in:
fiatjaf
2024-12-31 23:09:56 -03:00
parent dcd5030fcd
commit 08d6943dd1

View File

@@ -1,6 +1,7 @@
package sdk
import (
"iter"
"regexp"
"strconv"
"strings"
@@ -21,20 +22,18 @@ type Reference struct {
var mentionRegex = regexp.MustCompile(`\bnostr:((note|npub|naddr|nevent|nprofile)1\w+)\b|#\[(\d+)\]`)
// ParseReferences parses both NIP-08 and NIP-27 references in a single unifying interface.
func ParseReferences(evt *nostr.Event) []*Reference {
var references []*Reference
content := evt.Content
func ParseReferences(evt nostr.Event) iter.Seq[Reference] {
return func(yield func(Reference) bool) {
for _, ref := range mentionRegex.FindAllStringSubmatchIndex(evt.Content, -1) {
reference := &Reference{
Text: content[ref[0]:ref[1]],
reference := Reference{
Text: evt.Content[ref[0]:ref[1]],
Start: ref[0],
End: ref[1],
}
if ref[6] == -1 {
// didn't find a NIP-10 #[0] reference, so it's a NIP-27 mention
nip19code := content[ref[2]:ref[3]]
nip19code := evt.Content[ref[2]:ref[3]]
if prefix, data, err := nip19.Decode(nip19code); err == nil {
switch prefix {
@@ -58,7 +57,7 @@ func ParseReferences(evt *nostr.Event) []*Reference {
} else {
// it's a NIP-10 mention.
// parse the number, get data from event tags.
n := content[ref[6]:ref[7]]
n := evt.Content[ref[6]:ref[7]]
idx, err := strconv.Atoi(n)
if err != nil || len(evt.Tags) <= idx {
continue
@@ -101,8 +100,9 @@ func ParseReferences(evt *nostr.Event) []*Reference {
}
}
references = append(references, reference)
if !yield(reference) {
return
}
}
}
return references
}