2026-05-02 13:02:38 +08:00

68 lines
1.7 KiB
Go

package menu
import "hyapp-admin-server/internal/model"
type menuNode struct {
ID uint `json:"id"`
ParentID *uint `json:"parentId"`
Code string `json:"code"`
Label string `json:"label"`
Path string `json:"path"`
Icon string `json:"icon"`
PermissionCode string `json:"permissionCode"`
Sort int `json:"sort"`
Visible bool `json:"visible"`
Children []menuNode `json:"children,omitempty"`
}
func menuNodeFromModel(menu model.Menu) menuNode {
return menuNode{
ID: menu.ID,
ParentID: menu.ParentID,
Code: menu.Code,
Label: menu.Title,
Path: menu.Path,
Icon: menu.Icon,
PermissionCode: menu.PermissionCode,
Sort: menu.Sort,
Visible: menu.Visible,
Children: []menuNode{},
}
}
func buildMenuTree(menus []model.Menu) []menuNode {
nodes := map[uint]*menuNode{}
for _, item := range menus {
node := menuNodeFromModel(item)
nodes[item.ID] = &node
}
for _, item := range menus {
node := nodes[item.ID]
if item.ParentID != nil {
if parent, ok := nodes[*item.ParentID]; ok {
parent.Children = append(parent.Children, *node)
}
}
}
roots := make([]menuNode, 0)
for _, item := range menus {
if item.ParentID == nil {
roots = append(roots, *nodes[item.ID])
}
}
return roots
}
func pruneEmptyMenuGroups(menus []menuNode) []menuNode {
out := make([]menuNode, 0, len(menus))
for _, item := range menus {
item.Children = pruneEmptyMenuGroups(item.Children)
if item.Path != "" || len(item.Children) > 0 {
out = append(out, item)
}
}
return out
}