From 631fad23d83c0b4dc336078ca50536f837d4218f Mon Sep 17 00:00:00 2001 From: Mike Sawka Date: Thu, 14 Nov 2024 16:19:21 -0800 Subject: [PATCH] add new vdom.H() func and Filter/FilterIdx (#1291) --- pkg/vdom/vdom.go | 58 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) diff --git a/pkg/vdom/vdom.go b/pkg/vdom/vdom.go index b28755268..68873779a 100644 --- a/pkg/vdom/vdom.go +++ b/pkg/vdom/vdom.go @@ -56,6 +56,17 @@ func (e *VDomElem) Key() string { return "" } +func (e *VDomElem) WithKey(key string) *VDomElem { + if e == nil { + return nil + } + if e.Props == nil { + e.Props = make(map[string]any) + } + e.Props[KeyPropKey] = key + return e +} + func TextElem(text string) VDomElem { return VDomElem{Tag: TextTag, Text: text} } @@ -128,6 +139,33 @@ func mergeClassAttr(props *map[string]any, classAttr classAttrWrapper) { } } +func Classes(classes ...any) string { + var parts []string + for _, class := range classes { + switch c := class.(type) { + case nil: + continue + case string: + if c != "" { + parts = append(parts, c) + } + } + // Ignore any other types + } + return strings.Join(parts, " ") +} + +func H(tag string, props map[string]any, children ...any) *VDomElem { + rtn := &VDomElem{Tag: tag, Props: props} + if len(children) > 0 { + for _, part := range children { + elems := partToElems(part) + rtn.Children = append(rtn.Children, elems...) + } + } + return rtn +} + func E(tag string, parts ...any) *VDomElem { rtn := &VDomElem{Tag: tag} for _, part := range parts { @@ -206,6 +244,26 @@ func ForEachIdx[T any](items []T, fn func(T, int) any) []any { return elems } +func Filter[T any](items []T, fn func(T) bool) []T { + var elems []T + for _, item := range items { + if fn(item) { + elems = append(elems, item) + } + } + return elems +} + +func FilterIdx[T any](items []T, fn func(T, int) bool) []T { + var elems []T + for idx, item := range items { + if fn(item, idx) { + elems = append(elems, item) + } + } + return elems +} + func Props(props any) map[string]any { m, err := utilfn.StructToMap(props) if err != nil {