Playground
gnomod.toml
module = "gno.land/p/samcrew/urlfilter/v0" gno = "0.9" [addpkg] creator = "g1kfd9f5zlvcvy6aammcmqswa7cyjpu2nyt9qfen"
urlfilter.gno
// Package urlfilter provides functionality to filter items based on URL query parameters.
// It is designed to work with an avl.Tree structure where each key represents a filter
// and each value is an avl.Tree containing items associated with that filter.
package urlfilter
import (
"net/url"
"strings"
"gno.land/p/nt/bptree/v0"
"gno.land/p/nt/ufmt/v0"
"gno.land/p/sunspirit/md/v0"
)
// ApplyFilters filters items based on the "filter" query parameter in the given URL
// and generates a Markdown representation of all available filters.
//
// Expected `items` structure:
// - `items` is an *bptree.BPTree where each key is a filter name (e.g., "T1", "size:XL", "on_sale")
// and each value is an *bptree.BPTree containing the items for that filter.
// - Each item tree uses:
// Key (string): Unique item identifier
// Value (any) : Optional associated item data
//
// Example:
//
// // Build the main filters tree
// filters := bptree.NewBPTree32()
//
// // Subtree for filter "T1"
// t1Items := bptree.NewBPTree32()
// t1Items.Set("item1", nil)
// t1Items.Set("item2", nil)
// filters.Set("T1", t1Items)
//
// // URL with active filter "T1"
// u, _ := url.Parse("/shop?filter=T1")
//
// mdFilters, items := ApplyFilters(u, filters, "filter")
//
// // mdFilters → Markdown links for toggling filters
// // items → AVL tree containing the filtered items
func ApplyFilters(u *url.URL, items *bptree.BPTree, paramName string) (string, *bptree.BPTree) {
active := parseFilterMap(u.Query(), paramName)
allFilters := make([]string, 0)
resultTree := bptree.NewBPTree32()
// Iterate over each filter group in the items tree
items.Iterate("", "", func(filterKey string, subtree interface{}) bool {
allFilters = append(allFilters, filterKey)
tree, ok := subtree.(*bptree.BPTree)
if !ok {
return false
}
// Add items to result if there are no active filters
// or if the current filter is active
tree.Iterate("", "", func(itemKey string, _ interface{}) bool {
if len(active) == 0 || active[filterKey] {
resultTree.Set(itemKey, filterKey)
}
return false
})
return false
})
// Build Markdown links for toggling each filter
var sb strings.Builder
for _, f := range allFilters {
q := toggleFilterQuery(active, f, allFilters, paramName)
urlStr := buildURL(u.Path, q)
sb.WriteString(ufmt.Sprintf(" | %v ", md.Link(formatLabel(f, active[f]), urlStr)))
}
return sb.String(), resultTree
}
// buildURL returns a path + query string, omitting the "?" if no query exists.
func buildURL(path string, query url.Values) string {
if enc := query.Encode(); enc != "" {
return path + "?" + enc
}
return path
}
// parseFilterMap reads the "filter" query parameter and converts it into a map
// where keys are filter names and values are true for active filters.
//
// Example:
//
// "filter=T1,T2" -> map[string]bool{"T1": true, "T2": true}
func parseFilterMap(query url.Values, paramName string) map[string]bool {
filterStr := strings.TrimSpace(query.Get(paramName))
if filterStr == "" {
return map[string]bool{}
}
m := make(map[string]bool)
for _, f := range strings.Split(filterStr, ",") {
if f = strings.TrimSpace(f); f != "" {
m[f] = true
}
}
return m
}
// toggleFilterQuery returns a new query string with the given filter toggled.
// - If the filter is currently active, it will be removed.
// - If it is inactive, it will be added.
// The order of filters follows the `all` list for consistency.
func toggleFilterQuery(active map[string]bool, toggled string, all []string, paramName string) url.Values {
newFilters := []string{}
for _, f := range all {
if f == toggled {
if !active[f] { // Add if it was inactive
newFilters = append(newFilters, f)
}
} else if active[f] { // Keep other active filters
newFilters = append(newFilters, f)
}
}
q := url.Values{}
if len(newFilters) > 0 {
q.Set(paramName, strings.Join(newFilters, ","))
}
return q
}
// formatLabel returns the Markdown-formatted label for a filter,
// showing active filters in bold (**filter**) and inactive filters
// with strikethrough (~~filter~~).
func formatLabel(name string, active bool) string {
if active {
return md.Bold(name)
}
return md.Strikethrough(name)
}
urlfilter_test.gno
package urlfilter
import (
"net/url"
"strings"
"testing"
"gno.land/p/nt/bptree/v0"
)
func buildTestTree() *bptree.BPTree {
root := bptree.NewBPTree32()
// keyF1 subtree
t1 := bptree.NewBPTree32()
t1.Set("key1_1", nil)
t1.Set("key1_2", nil)
root.Set("keyF1", t1)
// keyF2 subtree
t2 := bptree.NewBPTree32()
t2.Set("key2_1", nil)
t2.Set("key2_2", nil)
root.Set("keyF2", t2)
return root
}
func TestApplyFilters(t *testing.T) {
TreeParent := buildTestTree()
// --- Case 1: No filter selected
u, _ := url.Parse("/test")
mdFilters, items := ApplyFilters(u, TreeParent, "filter")
expectedMarkdown := " | [~~keyF1~~](/test?filter=keyF1) | [~~keyF2~~](/test?filter=keyF2) "
if mdFilters != expectedMarkdown {
t.Errorf("Expected Markdown %q, got %q", expectedMarkdown, mdFilters)
}
// All items should be present
count := 0
items.Iterate("", "", func(k string, _ interface{}) bool {
count++
return false
})
if count != 4 {
t.Errorf("Expected 4 items, got %d", count)
}
// Try using ApplyFilters with a different name.
withCustom, _ := ApplyFilters(u, TreeParent, "custom-param-name")
if !strings.Contains(withCustom, "custom-param-name=keyF1") {
t.Errorf("Expected 'custom-param-name' parameter in Markdown, got %q", mdFilters)
}
// --- Case 2: One filter active (keyF1)
u, _ = url.Parse("/test?filter=keyF1")
mdFilters, items = ApplyFilters(u, TreeParent, "filter")
expectedMarkdown = " | [**keyF1**](/test) | [~~keyF2~~](/test?filter=keyF1%2CkeyF2) "
if mdFilters != expectedMarkdown {
t.Errorf("Expected Markdown %q, got %q", expectedMarkdown, mdFilters)
}
// Only keyF1 items should be present
keys := map[string]bool{}
items.Iterate("", "", func(k string, _ interface{}) bool {
keys[k] = true
return false
})
if len(keys) != 2 || !keys["key1_1"] || !keys["key1_2"] {
t.Errorf("Unexpected items in filtered result: %#v", keys)
}
// --- Case 3: Multiple filters active (keyF1, keyF2)
u, _ = url.Parse("/test?filter=keyF1,keyF2")
mdFilters, items = ApplyFilters(u, TreeParent, "filter")
// Both filters should be bold, no remove query for last one
if items.Size() != 4 {
t.Errorf("Expected 4 items, got %d", items.Size())
}
// --- Case 4: Filter not existing
u, _ = url.Parse("/test?filter=unknown")
mdFilters, items = ApplyFilters(u, TreeParent, "filter")
// No matching items
if items.Size() != 0 {
t.Errorf("Expected 0 items for unknown filter, got %d", items.Size())
}
}