component

package
v0.10.0 Latest Latest
Warning

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

Go to latest
Published: May 13, 2023 License: MIT Imports: 10 Imported by: 0

Documentation

Overview

Package component features a framework, inspired by React, that allows one to construct a user interface hierarchy through the usage of declarative DSL.

This package builds on top of the ui package and uses Elements as its foundation. The Elements are accessible only in some specific cases.

Index

Constants

This section is empty.

Variables

View Source
var Element = Define(func(props Properties, scope Scope) Instance {
	data := GetData[ElementData](props)

	element := UseState(func() *ui.Element {
		return Window(scope).CreateElement()
	}).Get()

	Once(func() {
		if data.Focused.Specified && data.Focused.Value {
			Window(scope).GrantFocus(element)
		}
	})

	Defer(func() {
		element.Destroy()
	})

	if data.Reference != nil {
		*data.Reference = element
	}

	element.SetEssence(data.Essence)
	if data.Enabled.Specified {
		element.SetEnabled(data.Enabled.Value)
	}
	if data.Visible.Specified {
		element.SetVisible(data.Visible.Value)
	}
	if data.Focusable.Specified {
		element.SetFocusable(data.Focusable.Value)
	}
	if data.Bounds.Specified {
		element.SetBounds(data.Bounds.Value)
	}
	if data.IdealSize.Specified {
		element.SetIdealSize(data.IdealSize.Value)
	}
	element.SetLayout(data.Layout)
	element.SetPadding(data.Padding)
	element.SetLayoutConfig(props.LayoutData())

	return Instance{
		element:  element,
		children: props.Children(),
	}
})

Element represents the most basic component, which is translated to a UI Element. All higher-order components eventually boil down to an Element.

Functions

func After

func After(duration time.Duration, fn func())

After will schedule a closure function to be run after the specified amount of time. The closure is guaranteed to run on the UI thread and the framework ensures that the closure will not be called if the component had been destroyed in the meantime.

Normally, you would use this function within a Once block or as a result of a callback. Not doing so would cause the closure function to be scheduled on every rendering of the component, since the framework is free to render a component at any time it deems necessary.

func CreateFont added in v0.8.0

func CreateFont(scope Scope, otFont *opentype.Font) *ui.Font

CreateFont uses the ui.Context from the specified scope to create a new ui.Font based on the passed opentype Font.

If creation of the font fails, this function logs an error and returns nil.

func CreateImage added in v0.3.0

func CreateImage(scope Scope, img image.Image) *ui.Image

CreateImage uses the ui.Context from the specified scope to create a new image.

If the image could not be created for some reason, this function logs an error and returns nil.

func Defer

func Defer(fn func())

Defer can be used to perform a cleanup action. The framework will issue one final render of a component before it gets destroyed. During that final render all closure functions specified via the Defer function will be invoked in the respective order.

Similar to Once, Defer can be used multiple times within a component's render function.

func GetCallbackData added in v0.5.0

func GetCallbackData[T any](props Properties) T

GetCallbackData returns the callback data stored in Properties as the specified type.

func GetContext added in v0.5.0

func GetContext[T any]() T

GetContext retrieves the appropriate context based on the generic type param and returns it.

func GetData added in v0.5.0

func GetData[T any](props Properties) T

GetData returns the data stored in Properties as the specified type.

func GetFont

func GetFont(scope Scope, family, style string) *ui.Font

GetFont uses the ui.Context from the specified scope to retrieve the font with the specified family and style.

This function returns nil and logs a warning if it is unable to find the requested font (fonts need to have been loaded beforehand through one of the other Font functions).

func GetLayoutData added in v0.5.0

func GetLayoutData[T any](props Properties) T

GetLayoutData returns the layout data stored in Properties as the specified type.

func GetOptionalCallbackData added in v0.5.0

func GetOptionalCallbackData[T any](props Properties, defaultValue T) T

GetOptionalCallbackData returns the callback data stored in Properties as the specified type, unless there is no callback data, in which case the defaultValue is returned.

func GetOptionalData added in v0.5.0

func GetOptionalData[T any](props Properties, defaultValue T) T

GetOptionalData returns the data stored in Properties as the specified type, unless there is no data, in which case the defaultValue is returned.

func GetOptionalLayoutData added in v0.5.0

func GetOptionalLayoutData[T any](props Properties, defaultValue T) T

GetOptionalLayoutData returns the layout data stored in Properties as the specified type, unless there is no layout data, in which case the defaultValue is returned.

func GetScopeValue added in v0.8.0

func GetScopeValue[T any](scope Scope, key interface{}) T

GetScopeValue is a helper function that retrieves the value as the specified generic param type from the specified scope using the provided key.

If there is no value with the specified key in the Scope or if the value is not of the correct type then nil is returned.

func Initialize

func Initialize(window *ui.Window, instance Instance)

Initialize wires the framework to the specified ui.Window. The specified Instance will be the root component used.

func InjectContext

func InjectContext[T any](target *T)

InjectContext retrieves the appropriate context and assigns it to target.

The specified target must be a pointer to the type that was used in RegisterContext.

func IsEqualData added in v0.3.0

func IsEqualData(old, new interface{}) bool

IsEqualData compares if the two data objects are equal

func Once

func Once(fn func())

Once can be used to perform an initialization action in a component's render function. During subsequent renders for the same component instance, the specified closure function will not be called.

You can use Once multiple times within a component's render function and all closure functions will be called in the respective order.

func OpenFont added in v0.6.0

func OpenFont(scope Scope, uri string) *ui.Font

OpenFont uses the ui.Context from the specified scope to load the font at the specified uri location.

If the font cannot be loaded for some reason, this function logs an error and returns nil.

func OpenFontCollection

func OpenFontCollection(scope Scope, uri string) *ui.FontCollection

OpenFontCollection uses the ui.Context from the specified scope to load the font collection at the specified uri location.

If the collection cannot be loaded for some reason, this function logs an error and returns nil.

func OpenImage

func OpenImage(scope Scope, uri string) *ui.Image

OpenImage uses the ui.Context from the specified scope to load image at the specified uri location.

If loading of the image fails for some reason, this function logs an error and returns nil.

func RegisterContext

func RegisterContext(value any)

RegisterContext registers a data structure that will be accessible from all components.

If used, this method should be called during bootstrapping and should not be called from within components.

The context is stored according to its type and there can only be one call per struct type. Once a context is set it is persisted for the whole lifecycle of the framework.

Contexts should be used only for global configurations that will not change, like graphics handles or i18n functions.

func Schedule

func Schedule(fn func())

Schedule will schedule a closure function to run as soon as possible on the UI thread.

Normally this would be used when a certain processing is being performed on a separate go routine and the result needs to be passed back to the UI thread.

The framework ensures that the closure will not be called if the component had been destroyed in the meantime.

func UseLifecycle added in v0.3.0

func UseLifecycle[T Lifecycle](constructor func(handle LifecycleHandle) T) T

UseLifecycle attaches a Lifecycle to the given Component instance in which this hook is used.

func Window

func Window(scope Scope) *ui.Window

Window uses the specified scope to retrieve the Window that owns that particular scope.

func WithCallbackData

func WithCallbackData(callbackData interface{})

WithCallbackData specifies the callback data to be passed to the component during instantiation.

Callback data is a mechanism for one component to listen for events on instanced components.

As callback data is expected to be a struct of function fields, they are not comparable in Go and as such cannot follow the lifecycle of data or layout data.

func WithChild

func WithChild(key string, instance Instance)

WithChild adds a child to the given component. The child is appended to all previously registered children via the same method.

The key property is important. If in a subsequent render a component's child changes key or component type, the old one will be destroyed and a new one will be created. As such, to maintain a more optimized rendering and to prevent state loss, children should have a key assigned to them.

func WithChildren

func WithChildren(children []Instance)

WithChildren sets the children for the given component. Keep in mind that any former children assigned via WithChild are replaced.

func WithData

func WithData(data interface{})

WithData specifies the data to be passed to the component during instantiation.

Your data should be comparable in order to enable optimizations done by the framework. If you'd like to pass functions, in case of callbacks, they can be passed through the callback data.

func WithLayoutData

func WithLayoutData(layoutData interface{})

WithLayoutData specifies the layout data to be passed to the component during instantiation.

LayoutData is kept separate by the framework as it is expected to have a different lifecycle (changes might be rare) and as such can be optimized.

Your layout data should be comparable in order to enable optimizations done by the framework.

func WithScope added in v0.8.0

func WithScope(scope Scope)

WithScope attaches a custom Scope to this component. Any child components will inherit the Scope unless overridden by another call to WithScope.

func XWithCallbackData added in v0.8.0

func XWithCallbackData(callbackData interface{})

XWithCallbackData is a helper function that resembles WithCallbackData but does nothing. This allows one to experiment during development without having to comment out large sections of code and deal with compilation issues.

func XWithChild added in v0.8.0

func XWithChild(key string, instance Instance)

XWithChild is a helper function that resembles WithChild but does nothing. This allows one to experiment during development without having to comment out large sections of code and deal with compilation issues.

func XWithChildren added in v0.8.0

func XWithChildren(children []Instance)

XWithChildren is a helper function that resembles WithChildren but does nothing. This allows one to experiment during development without having to comment out large sections of code and deal with compilation issues.

func XWithData added in v0.8.0

func XWithData(data interface{})

XWithData is a helper function that resembles WithData but does nothing. This allows one to experiment during development without having to comment out large sections of code and deal with compilation issues.

func XWithLayoutData added in v0.8.0

func XWithLayoutData(layoutData interface{})

XWithLayoutData is a helper function that resembles WithLayoutData but does nothing. This allows one to experiment during development without having to comment out large sections of code and deal with compilation issues.

func XWithScope added in v0.8.0

func XWithScope(scope Scope)

XWithScope is a helper function that resembles WithScope but does nothing. This allows one to experiment during development without having to comment out large sections of code and deal with compilation issues.

Types

type BaseLifecycle added in v0.3.0

type BaseLifecycle struct{}

BaseLifecycle is an implementation of Lifecycle that does nothing.

func NewBaseLifecycle added in v0.3.0

func NewBaseLifecycle() *BaseLifecycle

NewBaseLifecycle returns a new BaseLifecycle.

func (*BaseLifecycle) OnCreate added in v0.3.0

func (l *BaseLifecycle) OnCreate(props Properties, scope Scope)

func (*BaseLifecycle) OnDestroy added in v0.3.0

func (l *BaseLifecycle) OnDestroy(scope Scope)

func (*BaseLifecycle) OnUpdate added in v0.3.0

func (l *BaseLifecycle) OnUpdate(props Properties, scope Scope)

type Component

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

Component represents the definition of a component.

func ContextScoped added in v0.8.0

func ContextScoped(delegate Component) Component

ContextScoped will cause a wrapped component to receive a Scope that has a dedicated ui.Context with a lifecycle equal to the lifecycle of the component instance.

func Define

func Define(fn ComponentFunc) Component

Define is the mechanism through which new components can be defined.

The provided component function (i.e. render function) will be called by the framework to initialize, reconcicle,or destroy a component instance.

func DefineType added in v0.10.0

func DefineType(template TypeComponent) Component

DefineType defines a new component using the specified Go type as template.

type ComponentFunc

type ComponentFunc func(props Properties, scope Scope) Instance

ComponentFunc is the mechanism through which components can construct their hierarchies based on input properties and scope.

type CreateNotifiable added in v0.10.0

type CreateNotifiable interface {

	// OnCreate is called when a component is first instantiated.
	OnCreate()
}

CreateNotifiable should be implemented by TypeComponent types that want to be notified of component creation.

type DeleteNotifiable added in v0.10.0

type DeleteNotifiable interface {

	// OnDelete is called just before a component is destroyed.
	OnDelete()
}

DeleteNotifiable should be implemented by TypeComponent types that want to be notified of component deletion.

type ElementData

type ElementData struct {
	Reference **ui.Element
	Essence   ui.Essence
	Enabled   opt.T[bool]
	Visible   opt.T[bool]
	Focusable opt.T[bool]
	Focused   opt.T[bool]
	Bounds    opt.T[ui.Bounds]
	IdealSize opt.T[ui.Size]
	Padding   ui.Spacing
	Layout    ui.Layout
}

ElementData is the struct that should be used when configuring an Element component's data.

type Instance

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

Instance represents the instantiation of a given Component.

func New

func New(component Component, setupFn func()) Instance

New instantiates the specified component. The setupFn function is used to apply configurations to the component in a DSL manner.

NOTE: Creating an instance with New does not necessarily mean that a component will be freshly instantiated. If this occurs during re-rendering the framework will reuse former instances when possible.

func (Instance) Key added in v0.3.0

func (i Instance) Key() string

Key returns the child key that is registered for this Instance in case the Instance was created as part of a WithChild directive.

type Lifecycle added in v0.3.0

type Lifecycle interface {

	// OnCreate is called when the Component instance is first created.
	OnCreate(props Properties, scope Scope)

	// OnUpdate is called when an existing Component instance has its properties
	// changed.
	OnUpdate(props Properties, scope Scope)

	// OnDestroy is called when the Component is about to be detached and removed.
	OnDestroy(scope Scope)
}

Lifecycle is a mechanism through which a Component may get more detailed lifecycle events.

type LifecycleHandle added in v0.3.0

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

LifecycleHandle is a hook through which a Lifecycle can invalidate a Component, as though the Component's data were changed.

func (LifecycleHandle) NotifyChanged added in v0.3.0

func (h LifecycleHandle) NotifyChanged()

NotifyChanged invalidates the Component instance.

type Overlay added in v0.3.0

type Overlay interface {

	// Close closes this Overlay.
	Close()
}

Overlay represents a UI Element that stays on top of all existing elements and is first to receive events.

func OpenOverlay added in v0.3.0

func OpenOverlay(scope Scope, instance Instance) Overlay

OpenOverlay opens a new Overlay that will take the appearance described in the specified instance.

type Properties

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

Properties is a holder for all user-specified data necessary to render a component.

func (Properties) CallbackData

func (p Properties) CallbackData() interface{}

CallbackData returns the callback data that can be used by the component to notify its instantiator regarding key events.

func (Properties) Children

func (p Properties) Children() []Instance

Children returns all the child instances that this component should host.

func (Properties) Data

func (p Properties) Data() interface{}

Data returns the configuration data needed to render the component.

func (Properties) InjectCallbackData

func (p Properties) InjectCallbackData(target interface{})

InjectCallbackData is a helper function that injects the CallbackData into the specified target, which should be a pointer to the correct type.

func (Properties) InjectData

func (p Properties) InjectData(target interface{})

InjectData is a helper function that injects the Data into the specified target, which should be a pointer to the correct type.

func (Properties) InjectLayoutData

func (p Properties) InjectLayoutData(target interface{})

InjectLayoutData is a helper function that injects the LayoutData into the specified target, which should be a pointer to the correct type.

func (Properties) InjectOptionalCallbackData

func (p Properties) InjectOptionalCallbackData(target, defaultValue interface{})

InjectOptionalCallbackData is a helper function that injects the CallbackData into the specified target, which should be a pointer to the correct type, or if there is no callback data, it injects the defaultValue one.

func (Properties) InjectOptionalData

func (p Properties) InjectOptionalData(target, defaultValue interface{})

InjectOptionalData is a helper function that injects the Data into the specified target, which should be a pointer to the correct type, or if there is no data, it injects the default one.

func (Properties) InjectOptionalLayoutData

func (p Properties) InjectOptionalLayoutData(target, defaultValue interface{})

InjectOptionalLayoutData is a helper function that injects the LayoutData into the specified target, which should be a pointer to the correct type, or if there is no layout data, it injects the defaultValue one.

func (Properties) LayoutData

func (p Properties) LayoutData() interface{}

LayoutData returns the layout data needed to layout the component.

type Scope added in v0.8.0

type Scope interface {

	// Context returns the ui.Context that is applicable for this component scope.
	Context() *ui.Context

	// Value returns the stored arbitrary value for the specified arbitrary key.
	// This is a mechanism through which external frameworks can attach metadata
	// to scopes.
	Value(key interface{}) interface{}
}

Scope represents a component sub-hierarchy region.

func ContextScope added in v0.8.0

func ContextScope(parent Scope, ctx *ui.Context) Scope

ContextScope returns a new Scope that extends the specified parent scope but uses a different ui.Context. This can be used to have sections of the UI use a dedicated resource set that will be freed once the hierarchy is destroyed.

func RootScope added in v0.8.0

func RootScope() Scope

RootScope returns the main scope for the UI hierarchy. Resources loaded from the ui.Context of this scope will not be released until the UI has completed.

func ValueScope added in v0.8.0

func ValueScope(parent Scope, key, value interface{}) Scope

ValueScope creates a new Scope that extends the specified parent scope by adding the specified key-value pair.

type State

type State[T any] struct {
	// contains filtered or unexported fields
}

State represents a persistent state of a component. Every render operation for a component would return the same sequence of states.

func UseState

func UseState[T any](fn func() T) *State[T]

UseState registers a new State object to the given component.

During component initialization, the closure function will be called to retrieve an initial value to be assigned to the State.

The order in which this function is called inside a component's render function is important. As such, every component render should issue exactly the same UseState calls and in the exacly the same order.

func (*State[T]) Get

func (s *State[T]) Get() T

Ge returns the current value stored in this State.

func (*State[T]) Set

func (s *State[T]) Set(value T)

Set changes the value stored in this State. Using this function will force the component to be scheduled for reconciliation.

type TypeComponent added in v0.10.0

type TypeComponent interface {

	// Render should produce the UI hierarchy for this component.
	Render() Instance
}

TypeComponent is a component that is implemented through a Go type.

type UpdateNotifiable added in v0.10.0

type UpdateNotifiable interface {

	// OnUpdate is called whenever a component's properties have changed.
	OnUpdate()
}

UpdateNotifiable should be implemented by TypeComponent types that want to be notified of component update.

Jump to

Keyboard shortcuts

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