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