menu

package module
v0.0.0-...-179b311 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 7, 2024 License: MIT Imports: 7 Imported by: 0

README

Menu

Installation

go get -u github.com/gowool/menu

License

Distributed under MIT License, please see license file within the code for more details.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrItemBelongsToAnotherMenu = errors.New("cannot add menu item as child, it already belongs to another menu (e.g. has a parent)")
View Source
var ErrUnsupported = errors.New("unsupported data")

ErrUnsupported represents an error indicating unsupported data.

Functions

This section is empty.

Types

type CoreMatcher

type CoreMatcher struct {
	// contains filtered or unexported fields
}

CoreMatcher represents a matcher that determines the current state of an item.

func NewCoreMatcher

func NewCoreMatcher(voters ...Voter) *CoreMatcher

NewCoreMatcher creates a new instance of the CoreMatcher with the given voters. It initializes the cache with an empty map. The voters are used to determine whether an item is current. The CoreMatcher has the following methods: - IsCurrent: checks if an item is current based on the registered voters. - IsAncestor: checks if an item is an ancestor of any current items within a certain depth. - Clear: clears the cache.

Example usage:

v := NewCoreMatcher(voter1, voter2)
isCurrent := v.IsCurrent(ctx, item)

Parameters:

  • voters: a list of Voter implementations.

Returns:

  • Pointer to the initialized CoreMatcher.

func (*CoreMatcher) Clear

func (m *CoreMatcher) Clear()

Clear eliminates all the items from the cache map, synchronizing the access with a read-write lock.

func (*CoreMatcher) IsAncestor

func (m *CoreMatcher) IsAncestor(ctx context.Context, item *Item, depth *int) bool

IsAncestor checks whether the given item is an ancestor of any current item in the hierarchy, up to the specified depth. If the depth is not nil, it first checks if the depth is zero. If it is, it returns false. Then, it iterates over each child of the given item. If the child is a current item or an ancestor (recursive call to IsAncestor), it returns true. If none of the children match the condition, it returns false.

func (*CoreMatcher) IsCurrent

func (m *CoreMatcher) IsCurrent(ctx context.Context, item *Item) bool

IsCurrent checks whether an item is considered current.

If the "Current" field of the item is not nil, it returns the value of the field. If the item is found in the cache, it returns the cached value. Otherwise, it iterates over the registered voters and calls the "MatchItem" method on each voter. If a voter returns a non-nil value, it considers the item as current and breaks the loop. It then caches the value and returns it.

type Item

type Item struct {
	Name               string         `json:"name,omitempty"`
	URI                string         `json:"uri,omitempty"`
	Label              string         `json:"label,omitempty"`
	Position           int            `json:"position,omitempty"`
	DisplayChildren    bool           `json:"display_children,omitempty"`
	Display            bool           `json:"display,omitempty"`
	Current            *bool          `json:"current,omitempty"`
	Attributes         map[string]any `json:"attributes,omitempty"`
	LinkAttributes     map[string]any `json:"link_attributes,omitempty"`
	ChildrenAttributes map[string]any `json:"children_attributes,omitempty"`
	LabelAttributes    map[string]any `json:"label_attributes,omitempty"`
	Extras             map[string]any `json:"extras,omitempty"`
	Parent             *Item          `json:"parent,omitempty"`
	Children           []*Item        `json:"children,omitempty"`
}

Item represents an item in a menu.

func Must

func Must(item *Item, err error) *Item

func NewItem

func NewItem(name string, options ...Option) (*Item, error)

NewItem creates a new Item with the specified name and options. It initializes the Item with default attribute maps and sets the Display and DisplayChildren fields to true. The function applies each option to the Item sequentially, returning an error if any of the options fail. If successful, it returns the created Item and a nil error.

func (*Item) ActsLikeFirst

func (i *Item) ActsLikeFirst() bool

ActsLikeFirst checks if an Item acts like the first item in the menu hierarchy.

func (*Item) ActsLikeLast

func (i *Item) ActsLikeLast() bool

func (*Item) AddChild

func (i *Item) AddChild(child any, options ...Option) (childItem *Item, err error)

AddChild adds a child item to the current item. It accepts a `child` parameter of type `any`, which can be either an `*Item` or any other value. If `child` is an `*Item`, it checks if the child already belongs to another menu (i.e., it has a non-nil parent). If so, it returns an error `ErrItemBelongsToAnotherMenu`. Otherwise, it sets the parent of the child to the current item and appends the child to the list of children. If `child` is not an `*Item`, it creates a new item with a name obtained by formatting `child` as a string and using the options passed as variadic arguments. It sets the parent of the newly created child to the current item and appends it to the list of children. The method returns the child item added and a possible error.

func (*Item) Attribute

func (i *Item) Attribute(name string, def any) any

Attribute returns the value of the specified attribute from the Attributes map for the given item. If the attribute is not found, it returns the default value.

func (*Item) Child

func (i *Item) Child(name string) *Item

Child returns the child item with the specified name, if it exists. If no child with the given name is found, nil is returned.

func (*Item) ChildrenAttribute

func (i *Item) ChildrenAttribute(name string, def any) any

ChildrenAttribute returns the value of the provided attribute name from the ChildrenAttributes map of an Item. If the attribute is not found, it returns the default value.

func (*Item) Copy

func (i *Item) Copy() (*Item, error)

Copy creates a deep copy of the Item and its children.

func (*Item) Extra

func (i *Item) Extra(name string, def ...any) any

Extra returns the value of the specified extra info for an Item. If the info is not found, it returns the default value provided or nil.

func (*Item) FirstChild

func (i *Item) FirstChild() *Item

FirstChild returns the first child of an Item instance.

func (*Item) HasChildren

func (i *Item) HasChildren() bool

HasChildren checks if the item has any children that are set to be displayed.

func (*Item) IsCurrent

func (i *Item) IsCurrent() bool

IsCurrent returns true if the item is marked as current.

func (*Item) IsFirst

func (i *Item) IsFirst() bool

IsFirst returns true if the item is the first child of its parent, otherwise it returns false.

func (*Item) IsLast

func (i *Item) IsLast() bool

IsLast returns true if the item is the last child of its parent, false otherwise.

func (*Item) IsRoot

func (i *Item) IsRoot() bool

IsRoot returns true if the Item has no parent, indicating that it is the root item in the tree structure. Otherwise, it returns false.

func (*Item) LabelAttribute

func (i *Item) LabelAttribute(name string, def any) any

LabelAttribute returns the attribute value associated with the given name from the LabelAttributes map of the Item. If the attribute is not found, it returns the default value.

func (*Item) LastChild

func (i *Item) LastChild() *Item

LastChild returns the last child of the current item.

Example:

func (i *Item) IsLast() bool {
    if i.Parent == nil {
        return false
    }
    return i.Parent.LastChild() == i
}

func (*Item) Level

func (i *Item) Level() int

Level returns the level of the item in the hierarchy. If the item has no parent, it is considered to be at level 0. Each level is determined by the level of its parent item plus 1.

func (*Item) LinkAttribute

func (i *Item) LinkAttribute(name string, def any) any

LinkAttribute returns the value of the specified link attribute from the LinkAttributes map for the given item. If the attribute is not found, it returns the default value.

func (*Item) ReorderChildren

func (i *Item) ReorderChildren()

ReorderChildren sorts the child items of an Item based on their Position field. The sorting is done in ascending order.

func (*Item) Root

func (i *Item) Root() *Item

Root returns the root item of the item hierarchy. If the item has no parent, it is considered the root itself.

func (*Item) SetIsCurrent

func (i *Item) SetIsCurrent()

SetIsCurrent sets the IsCurrent property of an Item to true by assigning a pointer to a boolean value to its Current field.

func (*Item) SetNotCurrent

func (i *Item) SetNotCurrent()

SetNotCurrent sets the Current field of an Item to false.

func (*Item) String

func (i *Item) String() string

String returns the name of an Item. If the name is empty, it returns "n/a".

type Loader

type Loader interface {
	// Load loads the data and returns an *Item and an error. The ctx parameter is a context.Context object that can be used for cancellation or propagation of deadlines.
	Load(ctx context.Context, data any) (*Item, error)

	// Supports checks if the loader supports the given data. It returns `true` if the loader supports the data, otherwise `false`.
	Supports(data any) bool
}

Loader is an interface that represents a data loader.

type Matcher

type Matcher interface {
	// IsCurrent checks whether an item is current
	IsCurrent(ctx context.Context, item *Item) bool

	// IsAncestor checks whether an item is the ancestor of a current item
	IsAncestor(ctx context.Context, item *Item, depth *int) bool

	// Clear clears the state of the matcher
	Clear()
}

Matcher represents an interface for matching items. It provides methods for checking whether an item is current or an ancestor. It also provides a method for clearing the state of the matcher.

type Node

type Node interface {
	Name() string
	Options() []Option
	Children() []Node
}

type NodeLoader

type NodeLoader struct{}

NodeLoader represents a data loader for nodes.

func NewNodeLoader

func NewNodeLoader() NodeLoader

NewNodeLoader returns a new instance of NodeLoader.

func (NodeLoader) Load

func (l NodeLoader) Load(ctx context.Context, data any) (*Item, error)

Load processes the given data and returns a new Item representing the loaded data and its children, if any. If the data is not of type Node, an error is returned. The context.Context

func (NodeLoader) Supports

func (l NodeLoader) Supports(data any) bool

Supports checks if the given data is of type Node. Returns true if it is, false otherwise.

type Option

type Option func(item *Item) error

Option represents a function that can be used to modify an Item. It takes a pointer to an Item and returns an error if any.

func WithAttribute

func WithAttribute(name string, value any) Option

WithAttribute sets the specified attribute name and value for an item. The attribute is stored in the item's Attributes map. The function returns an Option function, which can be used to apply the attribute to an item. An error is returned if the attribute cannot be set.

Parameters: - name: the name of the attribute - value: the value of the attribute

Returns: - Option: the option function to apply the attribute to an item

Example Usage: item := &Item{Name: "Example"} opt := WithAttribute("color", "red") err := opt(item)

if err != nil {
    log.Fatal(err)
}

fmt.Println(item) // Output: {Name: "Example", Attributes: {"color": "red"}}

func WithAttributes

func WithAttributes(attributes map[string]any) Option

WithAttributes is a function that returns an Option for setting the attributes of an Item. It takes a map of attribute names to values and updates the Attributes field of the Item with those values. The Option is a function that takes a pointer to an Item and returns an error. It sets the Attributes field of the Item and returns nil.

Example: item := &Item{Name: "example"} attributes := map[string]interface{}{"color": "red", "size": "large"} option := WithAttributes(attributes) err := option(item) // item.Attributes is now set to the provided attributes

func WithChild

func WithChild(child *Item, options ...Option) Option

WithChild is a function that returns an Option for adding a child Item to another Item. The child Item is passed as the first argument to WithChild, and additional options can be provided as variadic arguments. The child Item is added to the parent Item's Children slice. If the child Item already belongs to another parent, an error of type ErrItemBelongsToAnotherMenu is returned.

func WithChildren

func WithChildren(children []*Item, options ...Option) Option

WithChildren is a function that returns an Option for setting the children of an Item object. It takes a slice of *Item as the children parameter and an optional variadic parameter options of type Option. The function iterates over the children slice and adds each child to the Item object using the AddChild method. The children are added in the order provided in the slice. If any error occurs during the addition of a child, the function stops adding any more children and returns the error. If all children are successfully added, the function returns nil indicating no error. The Children field of the Item object is set to a new empty slice with the capacity equal to the length of the children slice before adding any children. The function signature is:

func WithChildren(children []*Item, options ...Option) Option {
    ...
}

func WithChildrenAttribute

func WithChildrenAttribute(name string, value any) Option

WithChildrenAttribute is a function that creates an Option to add a children attribute to an Item. It takes a name string and a value of type any as parameters. The Option function updates the item's ChildrenAttributes field with the given name and value, and returns nil.

Example usage: item := &Item{} option := WithChildrenAttribute("color", "red") err := option(item)

if err != nil {
 	fmt.Println("Error:", err)
}

func WithChildrenAttributes

func WithChildrenAttributes(attributes map[string]any) Option

WithChildrenAttributes is a function that returns an option to set the children attributes of an Item.

The attributes are provided as a map[string]any, where the keys are the attribute names and the values are the attribute values. These attributes will be set for the children of the Item.

The returned option function modifies the provided Item by setting its ChildrenAttributes field to the provided attributes.

Example usage:

attributes := map[string]any {
    "color": "blue",
    "size": 12,
}
option := WithChildrenAttributes(attributes)
item := &Item{}
option(item)

func WithCurrent

func WithCurrent(current *bool) Option

WithCurrent takes a pointer to a bool as its argument and returns an Option. The returned Option function sets the Current field of the provided Item to the value of the provided bool pointer. It returns nil error. Example usage: opt := WithCurrent(&current)

func WithDisplay

func WithDisplay(display bool) Option

WithDisplay is a function that returns an Option for setting the display property of an Item. The display property determines whether or not the Item is displayed. Parameters:

  • display: a boolean indicating whether the Item should be displayed (true) or hidden (false).

Returns:

  • an Option function that modifies the display property of an Item.

Example usage:

item := &Item{}
option := WithDisplay(true)
option(item)

Note: This function is part of the Option pattern, where an Option is a function that modifies the properties of an Item.

func WithDisplayChildren

func WithDisplayChildren(displayChildren bool) Option

WithDisplayChildren is a function that returns an Option, which is used to set the DisplayChildren field of an Item struct. Option is a function type that takes a pointer to an Item and returns an error. It is used to configure the properties of an Item.

func WithExtra

func WithExtra(name string, value any) Option

WithExtra adds extra information to an Item. The name parameter specifies the key of the extra information. The value parameter specifies the value of the extra information. It returns an Option function that can be used to apply the extra information to an Item.

func WithExtras

func WithExtras(extras map[string]any) Option

WithExtras is a function that returns an Option which sets the Extras field of an Item. The Extras field is a map[string]any that contains any additional data associated with the

func WithLabel

func WithLabel(label string) Option

WithLabel is a function that returns an Option for setting the label of an Item. The Option function updates the Item's Label field with the provided label parameter. It returns nil if the operation is successful, otherwise an error.

Example usage:

item := &Item{}
err := WithLabel("Example Label")(item)
if err != nil {
    fmt.Println("Error:", err)
    return
}
fmt.Println("Item label:", item.Label)

Parameters:

  • label: the label to be set for the Item

Returns:

  • Option: the Option function that sets the label of an Item
  • error: nil if the operation is successful, otherwise an error

func WithLabelAttribute

func WithLabelAttribute(name string, value any) Option

WithLabelAttribute is a function that creates an Option to add a label attribute to an Item. It takes a name string and a value any as parameters. The returned Option function adds the label attribute to the given Item by setting the value under the specified name in the LabelAttributes map. It returns an error if there is an issue adding the label attribute. Example usage:

option := WithLabelAttribute("color", "red")
item := &Item{}
err := option(item)

func WithLabelAttributes

func WithLabelAttributes(attributes map[string]any) Option

WithLabelAttributes sets the label attributes of an item with the given attributes. It returns an Option type function that can be used to modify an item. The attributes are provided as a map[string]any, where the keys are the attribute names and the values are the attribute values.

Example usage: item := &Item{} attributes := map[string]any{"class": "label"} option := WithLabelAttributes(attributes) option(item)

Parameters: - attributes: The label attributes to be set for the item.

Returns: - An Option function that sets the label attributes of the item.

func WithLinkAttribute

func WithLinkAttribute(name string, value any) Option

WithLinkAttribute is a function that defines an option for modifying the link attributes of an Item. It adds or updates the specified attribute and its value in the LinkAttributes

func WithLinkAttributes

func WithLinkAttributes(attributes map[string]any) Option

WithLinkAttributes is a function that returns an Option function to set the link attributes of an Item. The link attributes are specified as a map[string]any, where the keys are attribute names and the values are attribute values.

Usage example: attributes := map[string]any{"class": "link", "target": "_blank"} option := WithLinkAttributes(attributes) item := &Item{} option(item) fmt.Println(item.LinkAttributes) // Output: map[class:link target:_blank]

func WithParent

func WithParent(parent *Item) Option

WithParent is an option function that sets the parent of an Item. It takes a pointer to an Item as a parameter and assigns the given parent to it. It returns an error if any error occurs during the assignment.

func WithPosition

func WithPosition(position int) Option

WithPosition is a function that creates an Option for setting the Position field of an Item. The Position field represents the order in which the Item should be displayed. The option created by WithPosition takes an integer parameter representing the desired position. The option function sets the Position field of the provided Item to the specified position. Example usage: item := &Item{} option := WithPosition(1) option(item) After applying the option, the Item's Position field will be set to 1.

func WithSafeLabel

func WithSafeLabel(safeLabel bool) Option

WithSafeLabel is a function that returns an Option for setting the "safe_label" extra attribute of an Item.

func WithURI

func WithURI(uri string) Option

WithURI is a function that returns an Option for setting the URI of an Item.

type SimpleNode

type SimpleNode struct {
	// contains filtered or unexported fields
}

func NewSimpleNode

func NewSimpleNode(name string, options []Option, children []Node) SimpleNode

func (SimpleNode) Children

func (n SimpleNode) Children() []Node

func (SimpleNode) Name

func (n SimpleNode) Name() string

func (SimpleNode) Options

func (n SimpleNode) Options() []Option

type URLVoter

type URLVoter struct{}

URLVoter represents a type that implements the Voter interface for determining whether an item's URI matches a given URI. MatchItem checks whether an item's URI matches the URI provided in the context.

If the URLVoter is not able to determine a result, it should return nil to let other voters do the job. Usage example:

```go

func (v URLVoter) MatchItem(ctx context.Context, item *Item) *bool {
	if _url, ok := ctx.Value("url").(*url.URI); ok && _url.Path == item.URI {
		return &ok
	}
	return nil
}

```

func (URLVoter) MatchItem

func (v URLVoter) MatchItem(ctx context.Context, item *Item) *bool

MatchItem is a method of the URLVoter type that checks if the URI of an Item matches with the URI stored in the context. If the URLs match, it returns a pointer to a boolean value set to true. Otherwise, it returns nil. It takes in a context.Context and a pointer to an Item as parameters. The context should contain a value with the key "url" that is of type *url.URL. The item's URI is compared with the URI from the context's value.

Example usage:

item := &Item{URI: "/example"}
url, _ := url.Parse("/example")
ctx := context.WithValue(context.Background(), "url", url)
result := urlVoter.MatchItem(ctx, item)
if result != nil && *result {
    fmt.Println("URLs match!")
}

type Voter

type Voter interface {
	// MatchItem checks whether an item is current.
	//
	// If the voter is not able to determine a result,
	// it should return nil to let other voters do the job.
	MatchItem(ctx context.Context, item *Item) *bool
}

Voter represents an interface for determining whether an item is current.

MatchItem checks whether an item is current.

If the voter is not able to determine a result, it should return nil to let other voters do the job.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL