Debian Codegraph @

navigation/menu.go

raw
1 // Copyright 2024 The Hugo Authors. All rights reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 // Package navigation provides the menu functionality.
15 package navigation
16
17 import (
18 "html/template"
19 "slices"
20 "sort"
21
22 "github.com/gohugoio/hugo/common/hmaps"
23 "github.com/gohugoio/hugo/common/types"
24 "github.com/gohugoio/hugo/compare"
25 "github.com/gohugoio/hugo/config"
26 "github.com/mitchellh/mapstructure"
27
28 "github.com/spf13/cast"
29 )
30
31 var smc = newMenuCache()
32
33 // MenuEntry represents a menu item defined in either Page front matter
34 // or in the project config.
35 type MenuEntry struct {
36 // The menu entry configuration.
37 MenuConfig
38
39 // The menu containing this menu entry.
40 Menu string
41
42 // The URL value from front matter / config.
43 ConfiguredURL string
44
45 // The Page connected to this menu entry.
46 Page Page
47
48 // Child entries.
49 Children Menu
50 }
51
52 func (m *MenuEntry) URL() string {
53 // Check page first.
54 // In Hugo 0.86.0 we added `pageRef`,
55 // a way to connect menu items in project config to pages.
56 // This means that you now can have both a Page
57 // and a configured URL.
58 // Having the configured URL as a fallback if the Page isn't found
59 // is obviously more useful, especially in multilingual sites.
60 if !types.IsNil(m.Page) {
61 return m.Page.RelPermalink()
62 }
63
64 return m.ConfiguredURL
65 }
66
67 // SetPageValues sets the Page and URL values for this menu entry.
68 func SetPageValues(m *MenuEntry, p Page) {
69 m.Page = p
70 if m.MenuConfig.Name == "" {
71 m.MenuConfig.Name = p.LinkTitle()
72 }
73 if m.MenuConfig.Title == "" {
74 m.MenuConfig.Title = p.Title()
75 }
76 if m.MenuConfig.Weight == 0 {
77 m.MenuConfig.Weight = p.Weight()
78 }
79 }
80
81 // A narrow version of page.Page.
82 type Page interface {
83 LinkTitle() string
84 Title() string
85 RelPermalink() string
86 Path() string
87 Section() string
88 Weight() int
89 IsPage() bool
90 IsSection() bool
91 IsAncestor(other any) bool
92 Params() hmaps.Params
93 }
94
95 // Menu is a collection of menu entries.
96 type Menu []*MenuEntry
97
98 // Menus is a dictionary of menus.
99 type Menus map[string]Menu
100
101 // PageMenus is a dictionary of menus defined in the Pages.
102 type PageMenus map[string]*MenuEntry
103
104 // HasChildren returns whether this menu item has any children.
105 func (m *MenuEntry) HasChildren() bool {
106 return m.Children != nil
107 }
108
109 // KeyName returns the key used to identify this menu entry.
110 func (m *MenuEntry) KeyName() string {
111 if m.Identifier != "" {
112 return m.Identifier
113 }
114 return m.Name
115 }
116
117 func (m *MenuEntry) hopefullyUniqueID() string {
118 if m.Identifier != "" {
119 return m.Identifier
120 } else if m.URL() != "" {
121 return m.URL()
122 } else {
123 return m.Name
124 }
125 }
126
127 // isEqual returns whether the two menu entries represents the same menu entry.
128 func (m *MenuEntry) isEqual(inme *MenuEntry) bool {
129 return m.hopefullyUniqueID() == inme.hopefullyUniqueID() && m.Parent == inme.Parent
130 }
131
132 // isSameResource returns whether the two menu entries points to the same
133 // resource (URL).
134 func (m *MenuEntry) isSameResource(inme *MenuEntry) bool {
135 if m.isSamePage(inme.Page) {
136 return m.Page == inme.Page
137 }
138 murl, inmeurl := m.URL(), inme.URL()
139 return murl != "" && inmeurl != "" && murl == inmeurl
140 }
141
142 func (m *MenuEntry) isSamePage(p Page) bool {
143 if !types.IsNil(m.Page) && !types.IsNil(p) {
144 return m.Page == p
145 }
146 return false
147 }
148
149 // MenuConfig holds the configuration for a menu.
150 type MenuConfig struct {
151 Identifier string
152 Parent string
153 Name string
154 Pre template.HTML
155 Post template.HTML
156 URL string
157 PageRef string
158 Weight int
159 Title string
160 // User defined params.
161 Params hmaps.Params
162 }
163
164 // For internal use.
165
166 // This is for internal use only.
167 func (m Menu) Add(me *MenuEntry) Menu {
168 m = append(m, me)
169 // TODO(bep)
170 m.Sort()
171 return m
172 }
173
174 /*
175 * Implementation of a custom sorter for Menu
176 */
177
178 // A type to implement the sort interface for Menu
179 type menuSorter struct {
180 menu Menu
181 by menuEntryBy
182 }
183
184 // Closure used in the Sort.Less method.
185 type menuEntryBy func(m1, m2 *MenuEntry) bool
186
187 func (by menuEntryBy) Sort(menu Menu) {
188 ms := &menuSorter{
189 menu: menu,
190 by: by, // The Sort method's receiver is the function (closure) that defines the sort order.
191 }
192 sort.Stable(ms)
193 }
194
195 var defaultMenuEntrySort = func(m1, m2 *MenuEntry) bool {
196 if m1.Weight == m2.Weight {
197 c := compare.Strings(m1.Name, m2.Name)
198 if c == 0 {
199 return m1.Identifier < m2.Identifier
200 }
201 return c < 0
202 }
203
204 if m2.Weight == 0 {
205 return true
206 }
207
208 if m1.Weight == 0 {
209 return false
210 }
211
212 return m1.Weight < m2.Weight
213 }
214
215 func (ms *menuSorter) Len() int { return len(ms.menu) }
216 func (ms *menuSorter) Swap(i, j int) { ms.menu[i], ms.menu[j] = ms.menu[j], ms.menu[i] }
217
218 // Less is part of sort.Interface. It is implemented by calling the "by" closure in the sorter.
219 func (ms *menuSorter) Less(i, j int) bool { return ms.by(ms.menu[i], ms.menu[j]) }
220
221 // Sort sorts the menu by weight, name and then by identifier.
222 func (m Menu) Sort() Menu {
223 menuEntryBy(defaultMenuEntrySort).Sort(m)
224 return m
225 }
226
227 // Limit limits the returned menu to n entries.
228 func (m Menu) Limit(n int) Menu {
229 if len(m) > n {
230 return m[0:n]
231 }
232 return m
233 }
234
235 // ByWeight sorts the menu by the weight defined in the menu configuration.
236 func (m Menu) ByWeight() Menu {
237 const key = "menuSort.ByWeight"
238 menus, _ := smc.get(key, menuEntryBy(defaultMenuEntrySort).Sort, m)
239
240 return menus
241 }
242
243 // ByName sorts the menu by the name defined in the menu configuration.
244 func (m Menu) ByName() Menu {
245 const key = "menuSort.ByName"
246 title := func(m1, m2 *MenuEntry) bool {
247 return compare.LessStrings(m1.Name, m2.Name)
248 }
249
250 menus, _ := smc.get(key, menuEntryBy(title).Sort, m)
251
252 return menus
253 }
254
255 // Reverse reverses the order of the menu entries.
256 func (m Menu) Reverse() Menu {
257 const key = "menuSort.Reverse"
258 reverseFunc := func(menu Menu) {
259 for i, j := 0, len(menu)-1; i < j; i, j = i+1, j-1 {
260 menu[i], menu[j] = menu[j], menu[i]
261 }
262 }
263 menus, _ := smc.get(key, reverseFunc, m)
264
265 return menus
266 }
267
268 // Clone clones the menu entries.
269 // This is for internal use only.
270 func (m Menu) Clone() Menu {
271 return slices.Clone(m)
272 }
273
274 func DecodeConfig(in any) (*config.ConfigNamespace[map[string]MenuConfig, Menus], error) {
275 buildConfig := func(in any) (Menus, any, error) {
276 ret := Menus{}
277
278 if in == nil {
279 return ret, map[string]any{}, nil
280 }
281
282 menus, err := hmaps.ToStringMapE(in)
283 if err != nil {
284 return ret, nil, err
285 }
286 menus = hmaps.CleanConfigStringMap(menus)
287
288 for name, menu := range menus {
289 m, err := cast.ToSliceE(menu)
290 if err != nil {
291 return ret, nil, err
292 } else {
293 for _, entry := range m {
294 var menuConfig MenuConfig
295 if err := mapstructure.WeakDecode(entry, &menuConfig); err != nil {
296 return ret, nil, err
297 }
298 hmaps.PrepareParams(menuConfig.Params)
299 menuEntry := MenuEntry{
300 Menu: name,
301 MenuConfig: menuConfig,
302 }
303 menuEntry.ConfiguredURL = menuEntry.MenuConfig.URL
304
305 if ret[name] == nil {
306 ret[name] = Menu{}
307 }
308 ret[name] = ret[name].Add(&menuEntry)
309 }
310 }
311 }
312
313 return ret, menus, nil
314 }
315
316 return config.DecodeNamespace[map[string]MenuConfig](in, buildConfig)
317 }