diff options
Diffstat (limited to 'navigation')
-rw-r--r-- | navigation/menu.go | 319 | ||||
-rw-r--r-- | navigation/menu_cache.go | 113 | ||||
-rw-r--r-- | navigation/menu_cache_test.go | 81 | ||||
-rw-r--r-- | navigation/pagemenus.go | 232 |
4 files changed, 745 insertions, 0 deletions
diff --git a/navigation/menu.go b/navigation/menu.go new file mode 100644 index 000000000..50e51bcbe --- /dev/null +++ b/navigation/menu.go @@ -0,0 +1,319 @@ +// Copyright 2023 The Hugo Authors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Package navigation provides the menu functionality. +package navigation + +import ( + "html/template" + "sort" + + "github.com/gohugoio/hugo/common/maps" + "github.com/gohugoio/hugo/common/types" + "github.com/gohugoio/hugo/compare" + "github.com/gohugoio/hugo/config" + "github.com/mitchellh/mapstructure" + + "github.com/spf13/cast" +) + +var smc = newMenuCache() + +// MenuEntry represents a menu item defined in either Page front matter +// or in the site config. +type MenuEntry struct { + // The menu entry configuration. + MenuConfig + + // The menu containing this menu entry. + Menu string + + // The URL value from front matter / config. + ConfiguredURL string + + // The Page connected to this menu entry. + Page Page + + // Child entries. + Children Menu +} + +func (m *MenuEntry) URL() string { + + // Check page first. + // In Hugo 0.86.0 we added `pageRef`, + // a way to connect menu items in site config to pages. + // This means that you now can have both a Page + // and a configured URL. + // Having the configured URL as a fallback if the Page isn't found + // is obviously more useful, especially in multilingual sites. + if !types.IsNil(m.Page) { + return m.Page.RelPermalink() + } + + return m.ConfiguredURL +} + +// SetPageValues sets the Page and URL values for this menu entry. +func SetPageValues(m *MenuEntry, p Page) { + m.Page = p + if m.MenuConfig.Name == "" { + m.MenuConfig.Name = p.LinkTitle() + } + if m.MenuConfig.Title == "" { + m.MenuConfig.Title = p.Title() + } + if m.MenuConfig.Weight == 0 { + m.MenuConfig.Weight = p.Weight() + } +} + +// A narrow version of page.Page. +type Page interface { + LinkTitle() string + Title() string + RelPermalink() string + Path() string + Section() string + Weight() int + IsPage() bool + IsSection() bool + IsAncestor(other any) (bool, error) + Params() maps.Params +} + +// Menu is a collection of menu entries. +type Menu []*MenuEntry + +// Menus is a dictionary of menus. +type Menus map[string]Menu + +// PageMenus is a dictionary of menus defined in the Pages. +type PageMenus map[string]*MenuEntry + +// HasChildren returns whether this menu item has any children. +func (m *MenuEntry) HasChildren() bool { + return m.Children != nil +} + +// KeyName returns the key used to identify this menu entry. +func (m *MenuEntry) KeyName() string { + if m.Identifier != "" { + return m.Identifier + } + return m.Name +} + +func (m *MenuEntry) hopefullyUniqueID() string { + if m.Identifier != "" { + return m.Identifier + } else if m.URL() != "" { + return m.URL() + } else { + return m.Name + } +} + +// isEqual returns whether the two menu entries represents the same menu entry. +func (m *MenuEntry) isEqual(inme *MenuEntry) bool { + return m.hopefullyUniqueID() == inme.hopefullyUniqueID() && m.Parent == inme.Parent +} + +// isSameResource returns whether the two menu entries points to the same +// resource (URL). +func (m *MenuEntry) isSameResource(inme *MenuEntry) bool { + if m.isSamePage(inme.Page) { + return m.Page == inme.Page + } + murl, inmeurl := m.URL(), inme.URL() + return murl != "" && inmeurl != "" && murl == inmeurl +} + +func (m *MenuEntry) isSamePage(p Page) bool { + if !types.IsNil(m.Page) && !types.IsNil(p) { + return m.Page == p + } + return false +} + +// MenuConfig holds the configuration for a menu. +type MenuConfig struct { + Identifier string + Parent string + Name string + Pre template.HTML + Post template.HTML + URL string + PageRef string + Weight int + Title string + // User defined params. + Params maps.Params +} + +// For internal use. + +// This is for internal use only. +func (m Menu) Add(me *MenuEntry) Menu { + m = append(m, me) + // TODO(bep) + m.Sort() + return m +} + +/* + * Implementation of a custom sorter for Menu + */ + +// A type to implement the sort interface for Menu +type menuSorter struct { + menu Menu + by menuEntryBy +} + +// Closure used in the Sort.Less method. +type menuEntryBy func(m1, m2 *MenuEntry) bool + +func (by menuEntryBy) Sort(menu Menu) { + ms := &menuSorter{ + menu: menu, + by: by, // The Sort method's receiver is the function (closure) that defines the sort order. + } + sort.Stable(ms) +} + +var defaultMenuEntrySort = func(m1, m2 *MenuEntry) bool { + if m1.Weight == m2.Weight { + c := compare.Strings(m1.Name, m2.Name) + if c == 0 { + return m1.Identifier < m2.Identifier + } + return c < 0 + } + + if m2.Weight == 0 { + return true + } + + if m1.Weight == 0 { + return false + } + + return m1.Weight < m2.Weight +} + +func (ms *menuSorter) Len() int { return len(ms.menu) } +func (ms *menuSorter) Swap(i, j int) { ms.menu[i], ms.menu[j] = ms.menu[j], ms.menu[i] } + +// Less is part of sort.Interface. It is implemented by calling the "by" closure in the sorter. +func (ms *menuSorter) Less(i, j int) bool { return ms.by(ms.menu[i], ms.menu[j]) } + +// Sort sorts the menu by weight, name and then by identifier. +func (m Menu) Sort() Menu { + menuEntryBy(defaultMenuEntrySort).Sort(m) + return m +} + +// Limit limits the returned menu to n entries. +func (m Menu) Limit(n int) Menu { + if len(m) > n { + return m[0:n] + } + return m +} + +// ByWeight sorts the menu by the weight defined in the menu configuration. +func (m Menu) ByWeight() Menu { + const key = "menuSort.ByWeight" + menus, _ := smc.get(key, menuEntryBy(defaultMenuEntrySort).Sort, m) + + return menus +} + +// ByName sorts the menu by the name defined in the menu configuration. +func (m Menu) ByName() Menu { + const key = "menuSort.ByName" + title := func(m1, m2 *MenuEntry) bool { + return compare.LessStrings(m1.Name, m2.Name) + } + + menus, _ := smc.get(key, menuEntryBy(title).Sort, m) + + return menus +} + +// Reverse reverses the order of the menu entries. +func (m Menu) Reverse() Menu { + const key = "menuSort.Reverse" + reverseFunc := func(menu Menu) { + for i, j := 0, len(menu)-1; i < j; i, j = i+1, j-1 { + menu[i], menu[j] = menu[j], menu[i] + } + } + menus, _ := smc.get(key, reverseFunc, m) + + return menus +} + +// Clone clones the menu entries. +// This is for internal use only. +func (m Menu) Clone() Menu { + return append(Menu(nil), m...) +} + +func DecodeConfig(in any) (*config.ConfigNamespace[map[string]MenuConfig, Menus], error) { + buildConfig := func(in any) (Menus, any, error) { + ret := Menus{} + + if in == nil { + return ret, map[string]any{}, nil + } + + menus, err := maps.ToStringMapE(in) + if err != nil { + return ret, nil, err + } + menus = maps.CleanConfigStringMap(menus) + + for name, menu := range menus { + m, err := cast.ToSliceE(menu) + if err != nil { + return ret, nil, err + } else { + + for _, entry := range m { + var menuConfig MenuConfig + if err := mapstructure.WeakDecode(entry, &menuConfig); err != nil { + return ret, nil, err + } + maps.PrepareParams(menuConfig.Params) + menuEntry := MenuEntry{ + Menu: name, + MenuConfig: menuConfig, + } + menuEntry.ConfiguredURL = menuEntry.MenuConfig.URL + + if ret[name] == nil { + ret[name] = Menu{} + } + ret[name] = ret[name].Add(&menuEntry) + } + } + } + + return ret, menus, nil + + } + + return config.DecodeNamespace[map[string]MenuConfig](in, buildConfig) +} diff --git a/navigation/menu_cache.go b/navigation/menu_cache.go new file mode 100644 index 000000000..4287ed875 --- /dev/null +++ b/navigation/menu_cache.go @@ -0,0 +1,113 @@ +// Copyright 2021 The Hugo Authors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package navigation + +import ( + "sync" +) + +type menuCacheEntry struct { + in []Menu + out Menu +} + +func (entry menuCacheEntry) matches(menuList []Menu) bool { + if len(entry.in) != len(menuList) { + return false + } + for i, m := range menuList { + if !menuEqual(m, entry.in[i]) { + return false + } + } + + return true +} + +func newMenuCache() *menuCache { + return &menuCache{m: make(map[string][]menuCacheEntry)} +} + +func (c *menuCache) clear() { + c.Lock() + defer c.Unlock() + c.m = make(map[string][]menuCacheEntry) +} + +type menuCache struct { + sync.RWMutex + m map[string][]menuCacheEntry +} + +func menuEqual(m1, m2 Menu) bool { + if m1 == nil && m2 == nil { + return true + } + + if m1 == nil || m2 == nil { + return false + } + + if len(m1) != len(m2) { + return false + } + + if len(m1) == 0 { + return true + } + + for i := 0; i < len(m1); i++ { + if m1[i] != m2[i] { + return false + } + } + return true +} + +func (c *menuCache) get(key string, apply func(m Menu), menuLists ...Menu) (Menu, bool) { + return c.getP(key, func(m *Menu) { + if apply != nil { + apply(*m) + } + }, menuLists...) +} + +func (c *menuCache) getP(key string, apply func(m *Menu), menuLists ...Menu) (Menu, bool) { + c.Lock() + defer c.Unlock() + + if cached, ok := c.m[key]; ok { + for _, entry := range cached { + if entry.matches(menuLists) { + return entry.out, true + } + } + } + + m := menuLists[0] + menuCopy := append(Menu(nil), m...) + + if apply != nil { + apply(&menuCopy) + } + + entry := menuCacheEntry{in: menuLists, out: menuCopy} + if v, ok := c.m[key]; ok { + c.m[key] = append(v, entry) + } else { + c.m[key] = []menuCacheEntry{entry} + } + + return menuCopy, false +} diff --git a/navigation/menu_cache_test.go b/navigation/menu_cache_test.go new file mode 100644 index 000000000..9943db517 --- /dev/null +++ b/navigation/menu_cache_test.go @@ -0,0 +1,81 @@ +// Copyright 2021 The Hugo Authors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package navigation + +import ( + "sync" + "sync/atomic" + "testing" + + qt "github.com/frankban/quicktest" +) + +func createSortTestMenu(num int) Menu { + menu := make(Menu, num) + for i := 0; i < num; i++ { + m := &MenuEntry{} + menu[i] = m + } + return menu +} + +func TestMenuCache(t *testing.T) { + t.Parallel() + c := qt.New(t) + c1 := newMenuCache() + + changeFirst := func(m Menu) { + m[0].MenuConfig.Title = "changed" + } + + var o1 uint64 + var o2 uint64 + + var wg sync.WaitGroup + + var l1 sync.Mutex + var l2 sync.Mutex + + var testMenuSets []Menu + + for i := 0; i < 50; i++ { + testMenuSets = append(testMenuSets, createSortTestMenu(i+1)) + } + + for j := 0; j < 100; j++ { + wg.Add(1) + go func() { + defer wg.Done() + for k, menu := range testMenuSets { + l1.Lock() + m, ca := c1.get("k1", nil, menu) + c.Assert(ca, qt.Equals, !atomic.CompareAndSwapUint64(&o1, uint64(k), uint64(k+1))) + l1.Unlock() + m2, c2 := c1.get("k1", nil, m) + c.Assert(c2, qt.Equals, true) + c.Assert(menuEqual(m, m2), qt.Equals, true) + c.Assert(menuEqual(m, menu), qt.Equals, true) + c.Assert(m, qt.Not(qt.IsNil)) + + l2.Lock() + m3, c3 := c1.get("k2", changeFirst, menu) + c.Assert(c3, qt.Equals, !atomic.CompareAndSwapUint64(&o2, uint64(k), uint64(k+1))) + l2.Unlock() + c.Assert(m3, qt.Not(qt.IsNil)) + c.Assert("changed", qt.Equals, m3[0].Title) + } + }() + } + wg.Wait() +} diff --git a/navigation/pagemenus.go b/navigation/pagemenus.go new file mode 100644 index 000000000..6321a8a63 --- /dev/null +++ b/navigation/pagemenus.go @@ -0,0 +1,232 @@ +// Copyright 2019 The Hugo Authors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package navigation + +import ( + "fmt" + + "github.com/gohugoio/hugo/common/maps" + "github.com/gohugoio/hugo/common/types" + "github.com/mitchellh/mapstructure" + + "github.com/spf13/cast" +) + +type PageMenusProvider interface { + PageMenusGetter + MenuQueryProvider +} + +type PageMenusGetter interface { + Menus() PageMenus +} + +type MenusGetter interface { + Menus() Menus +} + +type MenuQueryProvider interface { + HasMenuCurrent(menuID string, me *MenuEntry) bool + IsMenuCurrent(menuID string, inme *MenuEntry) bool +} + +func PageMenusFromPage(p Page) (PageMenus, error) { + params := p.Params() + + ms, ok := params["menus"] + if !ok { + ms, ok = params["menu"] + } + + pm := PageMenus{} + + if !ok { + return nil, nil + } + + me := MenuEntry{} + SetPageValues(&me, p) + + // Could be the name of the menu to attach it to + mname, err := cast.ToStringE(ms) + + if err == nil { + me.Menu = mname + pm[mname] = &me + return pm, nil + } + + // Could be a slice of strings + mnames, err := cast.ToStringSliceE(ms) + + if err == nil { + for _, mname := range mnames { + me.Menu = mname + pm[mname] = &me + } + return pm, nil + } + + var wrapErr = func(err error) error { + return fmt.Errorf("unable to process menus for page %q: %w", p.Path(), err) + } + + // Could be a structured menu entry + menus, err := maps.ToStringMapE(ms) + if err != nil { + return pm, wrapErr(err) + } + + for name, menu := range menus { + menuEntry := MenuEntry{Menu: name} + if menu != nil { + ime, err := maps.ToStringMapE(menu) + if err != nil { + return pm, wrapErr(err) + } + if err := mapstructure.WeakDecode(ime, &menuEntry.MenuConfig); err != nil { + return pm, err + } + } + SetPageValues(&menuEntry, p) + pm[name] = &menuEntry + } + + return pm, nil +} + +func NewMenuQueryProvider( + pagem PageMenusGetter, + sitem MenusGetter, + p Page) MenuQueryProvider { + return &pageMenus{ + p: p, + pagem: pagem, + sitem: sitem, + } +} + +type pageMenus struct { + pagem PageMenusGetter + sitem MenusGetter + p Page +} + +func (pm *pageMenus) HasMenuCurrent(menuID string, me *MenuEntry) bool { + if !types.IsNil(me.Page) && me.Page.IsSection() { + if ok, _ := me.Page.IsAncestor(pm.p); ok { + return true + } + } + + if !me.HasChildren() { + return false + } + + menus := pm.pagem.Menus() + + if m, ok := menus[menuID]; ok { + for _, child := range me.Children { + if child.isEqual(m) { + return true + } + if pm.HasMenuCurrent(menuID, child) { + return true + } + } + } + + if pm.p == nil { + return false + } + + for _, child := range me.Children { + if child.isSamePage(pm.p) { + return true + } + + if pm.HasMenuCurrent(menuID, child) { + return true + } + } + + return false +} + +func (pm *pageMenus) IsMenuCurrent(menuID string, inme *MenuEntry) bool { + menus := pm.pagem.Menus() + + if me, ok := menus[menuID]; ok { + if me.isEqual(inme) { + return true + } + } + + if pm.p == nil { + return false + } + + if !inme.isSamePage(pm.p) { + return false + } + + // This resource may be included in several menus. + // Search for it to make sure that it is in the menu with the given menuId. + if menu, ok := pm.sitem.Menus()[menuID]; ok { + for _, menuEntry := range menu { + if menuEntry.isSameResource(inme) { + return true + } + + descendantFound := pm.isSameAsDescendantMenu(inme, menuEntry) + if descendantFound { + return descendantFound + } + + } + } + + return false +} + +func (pm *pageMenus) isSameAsDescendantMenu(inme *MenuEntry, parent *MenuEntry) bool { + if parent.HasChildren() { + for _, child := range parent.Children { + if child.isSameResource(inme) { + return true + } + descendantFound := pm.isSameAsDescendantMenu(inme, child) + if descendantFound { + return descendantFound + } + } + } + return false +} + +var NopPageMenus = new(nopPageMenus) + +type nopPageMenus int + +func (m nopPageMenus) Menus() PageMenus { + return PageMenus{} +} + +func (m nopPageMenus) HasMenuCurrent(menuID string, me *MenuEntry) bool { + return false +} + +func (m nopPageMenus) IsMenuCurrent(menuID string, inme *MenuEntry) bool { + return false +} |