page

package
v0.26.0 Latest Latest
Warning

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

Go to latest
Published: Apr 5, 2023 License: MIT Imports: 40 Imported by: 0

Documentation

Overview

Package page is the user-interface layer of goradd, and implements state management and rendering of an html page, as well as the framework for rendering controls.

To use the page package, you start by creating a form object, and then add controls to that form. You also should add a drawing template to define additional html for the form.

Index

Constants

View Source
const (
	FrameworkErrNone = iota
	// FrameworkErrNoTemplate indicates a template does not exist. The control will move on to other ways of rendering.
	// No message should be displayed.
	FrameworkErrNoTemplate
	// FrameworkErrRecordNotFound is a rare situation that might come up as a race condition error between viewing a
	// record, and actually editing it. If in the time between clicking on a record to see detail, and viewing the detail,
	// the record was deleted by another user, we would return this error.
	// In a REST environment, this is  404 error
	FrameworkErrRecordNotFound
)
View Source
const (
	ResponseControls       = "controls"
	ResponseCommandsHigh   = "commandsHigh"
	ResponseCommandsMedium = "commands"
	ResponseCommandsLow    = "commandsLow"
	ResponseCommandsFinal  = "commandsFinal"
	ResponseRegC           = "regc" // register control list
	ResponseHtml           = "html"
	ResponseValue          = "value"
	ResponseId             = "id"
	ResponseAttributes     = "attributes"
	ResponseCss            = "css"
	ResponseClose          = "winclose"
	ResponseLocation       = "loc"
	ResponseAlert          = "alert"
	ResponseStyleSheets    = "ss"
	ResponseJavaScripts    = "js"
)
View Source
const HtmlVarAction = "Goradd_Action"
View Source
const HtmlVarApistate = "__ApiState"
View Source
const HtmlVarPagestate = "Goradd__PageState"
View Source
const MaxStackDepth = 50
View Source
const RequiredErrorMessage string = "A value is required"
View Source
const UserPageCacheVersion = 10000

UserPageCacheVersion is a version number you can use as a starting point if you want to keep track of the page cache version yourself.

Variables

View Source
var ControlRegistrySalt = "goradd"

ControlRegistrySalt is used to generate unique ids in the control registry. However, if the control registry detects a collision, you will need to change this value and restart your app. If you have a running page cache, you should change the PageCacheVersion above as well to invalidate it.

View Source
var DefaultCheckboxLabelDrawingMode = html5tag.LabelAfter

DefaultCheckboxLabelDrawingMode is a setting used by checkboxes and radio buttons to default how they draw labels. Some CSS frameworks are very picky about whether checkbox labels wrap the control, or sit next to the control, and whether the label is before or after the control

View Source
var HtmlErrorMessage = `` /* 198-byte string literal not displayed */
View Source
var MultipartFormMax int64 = 10000000 // 10MB max in memory file

MultipartFormMax is the maximum size of a mult-part form that we will allow.

View Source
var PageCacheVersion int32 = 1

PageCacheVersion helps us keep track of when a change to the application changes the pagecache format. It is only needed when serializing the pagecache. Some page cache stores may be difficult to invalidate the whole thing, so this lets lets us invalidate old pagecaches individually. Feel free to bump this as needed, though you should use a number after UserPageCacheVersion so there is no conflict with the goradd default.

View Source
var PagePathPrefix = ""

PagePathPrefix is a prefix you can use in front of all goradd pages, like a directory path, to indicate that this is a goradd path.

Functions

func ConvertToBool

func ConvertToBool(v interface{}) bool

ConvertToBool is a helper function that can convert Put or Get values and other possible kinds of values into a bool value.

func HasPage added in v0.5.0

func HasPage(pageStateId string) bool

func NewMockContext added in v0.0.3

func NewMockContext() (ctx context.Context)

NewMockContext creates a context for testing.

func Nodes added in v0.9.3

func Nodes(n ...query.NodeI) []query.NodeI

Nodes is used by Creators to specify a list of nodes.

func OutputLen added in v0.18.0

func OutputLen(ctx context.Context) int

OutputLen returns the number of bytes that have been written to the output.

func PageTmpl

func PageTmpl(ctx context.Context, page *Page, _w io.Writer) (err error)

PageTmpl is the template used to draw the initial html of a page, including the doctype tag, html tag, head and body tag.

func PutContext

func PutContext(r *http.Request, cliArgs []string) *http.Request

PutContext is used by the framework to insert the goradd context as a value in the standard GO context. You should not normally call this, unless you are customizing how your http server works.

func RegisterControl added in v0.3.0

func RegisterControl(i ControlI)

RegisterControl registers the control for the serialize/deserialize process. You should call this for each control from an init() function.

As a control is added to the registry, it is assigned an id. That id is used to identify a control in the serialization and deserialization process. We make a significant attempt to prevent the addition of controls to an application from causing a change in these ids, since an id change will also cause the current page cache to be invalidated. We use a hashing function, and a collision detector to do that. If a collision is detected, it will panic, and you should change the hash salt and try again, as well as bump the cache version to invalidate the cache.

func RegisterForm added in v0.5.0

func RegisterForm(path string, form FormI, id string)

RegisterForm associates the given URL path with the given form and form id and registers it with page manager. Call this from an init() function. Afterwards, whenever a user navigates to the given path, the form will be created and presented to the user.

func RegisterTemplate

func RegisterTemplate(name string, t TemplateExecuter)

func ResetOutputBuffer added in v0.18.0

func ResetOutputBuffer(ctx context.Context) []byte

func SetPageEncoder

func SetPageEncoder(e PageEncoderI)

func SetPageManager added in v0.5.0

func SetPageManager(p PageManagerI)

SetPageManager injects a new page manager. Call this at init time.

func SetPagestateCache added in v0.13.2

func SetPagestateCache(c PagestateCacheI)

SetPagestateCache will set the page cache to the given object.

func WriteString added in v0.18.0

func WriteString(w io.Writer, s string)

WriteString is a utility function that will write a string and panic if an error occurs

Types

type AppContext

type AppContext struct {

	// NoJavaScript indicates javascript is turned off by the browser
	NoJavaScript bool
	// contains filtered or unexported fields
}

AppContext has Goradd application specific information.

type Context

type Context struct {
	HttpContext
	AppContext
}

Context is the page context that we embed in the context.Context object that is passed throughout the application, and contains the per-request information that needs to be sent to various parts of the program. It primarily consists of items that we unpack from the http request. To get to it, simply call GetContext(ctx), where ctx is the context taken from the http request. The framework will take care of setting this up when a request is received.

func GetContext

func GetContext(ctx context.Context) *Context

GetContext returns the page context from the GO context.

func (*Context) ClientTimezone added in v0.19.0

func (ctx *Context) ClientTimezone() string

ClientTimezone returns the name of the timezone of the client, if available.

func (*Context) ClientTimezoneOffset added in v0.19.0

func (ctx *Context) ClientTimezoneOffset() int

ClientTimezoneOffset returns the number of minutes offset from GMT for the client's timezone.

func (*Context) CustomControlValue

func (ctx *Context) CustomControlValue(id string, key string) interface{}

CustomControlValue returns the value of a control that is using the custom control mechanism to report its values. You would only call this if your are implementing a control that has custom javascript to operate its UI.

func (*Context) FormValue

func (ctx *Context) FormValue(key string) (value string, ok bool)

FormValue returns the given form variable value, either from post or get variables. If the value does not exist, or is a multi-part value, returns false in ok. Use FormValues for multipart values.

func (*Context) FormValues

func (ctx *Context) FormValues(key string) (value []string, ok bool)

FormValues returns the corresponding form value as a string slice. Use this when you are expecting more than one value in the given form variable

func (*Context) HasCustomControlValue added in v0.12.0

func (ctx *Context) HasCustomControlValue(id string, key string) bool

HasCustomControlValue returns true if the given controls has a value for the given key. If you are potentially expecting a nil value, you can use this to know that a value is present.

func (*Context) HasTimezoneInfo added in v0.25.2

func (ctx *Context) HasTimezoneInfo() bool

HasTimezoneInfo returns true if timezone info is valid.

func (*Context) RequestMode

func (ctx *Context) RequestMode() RequestMode

RequestMode returns the request mode of the current request.

func (*Context) String

func (ctx *Context) String() string

String is a string representation of all the information in the context, and should primarily be used for debugging.

type ControlBase added in v0.4.0

type ControlBase struct {
	base.Base

	// Tag is text of the tag that will enclose the control, like "div" or "input"
	Tag string
	// IsVoidTag should be true if the tag should not have a closing tag, like "img"
	IsVoidTag bool

	// ErrorForRequired is the error that will display if a control value is required but not set.
	ErrorForRequired string

	// ValidMessage is the message to display if the control has successfully been validated.
	// Leave blank if you don't want a message to show when valid.
	// Can be useful to contrast between invalid and valid controls in a busy form.
	ValidMessage string
	// contains filtered or unexported fields
}

ControlBase is the basis for UI controls and widgets in GoRADD. It corresponds to a standard html form object or tag, or a custom javascript widget. A Control renders a tag and everything inside the tag, but can also include a wrapper which associates a label, instructions and error messages with the tag. A Control can also associate javascript with itself to make sure the javascript is loaded on the page when the control is drawn, and can render javascript that will initialize a custom javascript widget.

A Control can have child Controls. It can either allow the framework to automatically draw the child Controls as part of the inner-html of the ControlBase, can use a template to draw the Child controls, or manually draw them. Controls form a hierarchical tree structure, with the Form control being the root of the tree.

A Control is part of a system that will reflect the state of the control between the client and server. When a user updates a control in the browser and performs an action that requires a response from the server, the GoRADD javascript will gather all the changes in the form and send those to the server. The control can read those values and update its own internal state, so that from the perspective of the programmer referring to the control, the values in the Control are the same as what the user sees in a browser.

This ControlBase struct is a mixin that all controls should use. You would not normally create a ControlBase directly, but rather create one of the "subclasses" of ControlBase. See the [control] package for basic control implementations.

func (*ControlBase) ActionValue added in v0.4.0

func (c *ControlBase) ActionValue() interface{}

ActionValue returns the control's action value that is sent to the Action function in the ControlActionValue of the action.Params struct.

func (*ControlBase) AddClass added in v0.4.0

func (c *ControlBase) AddClass(class string) ControlI

AddClass will add a class or classes to the control. If adding multiple classes at once, separate them with a space.

func (*ControlBase) AddControls added in v0.4.0

func (c *ControlBase) AddControls(ctx context.Context, creators ...Creator)

AddControls adds sub-controls to a control using a Create function

func (*ControlBase) AddRelatedRenderScript added in v0.4.0

func (c *ControlBase) AddRelatedRenderScript(id string, f string, params ...interface{})

AddRelatedRenderScript adds a render script for a related html object. This is primarily used by control implementations.

func (*ControlBase) AddRenderScript added in v0.4.0

func (c *ControlBase) AddRenderScript(f string, params ...interface{})

AddRenderScript adds a javascript command to be executed on the next ajax draw. These commands allow javascript to change an aspect of the control without having to redraw the entire control. This should be used by ControlBase implementations only.

func (*ControlBase) ApplyOptions added in v0.4.0

func (c *ControlBase) ApplyOptions(ctx context.Context, o ControlOptions)

ApplyOptions is called by Creators to apply the default control options.

func (*ControlBase) Attribute added in v0.4.0

func (c *ControlBase) Attribute(name string) string

Attribute returns the value of a custom attribute. Note that this will not return values that are set only during drawing and that are managed by the ControlBase implementation.

func (*ControlBase) Attributes added in v0.4.0

func (c *ControlBase) Attributes() html5tag.Attributes

Attributes returns a pointer to the attributes of the control. Use this with caution. Some controls setup attributes at initialization time, so you could potentially write over those. Also, if you change attributes during an ajax call, the changes will not be reflected unless you redraw the control. The primary use for this function is to allow controls to set up attributes during initialization.

func (*ControlBase) Child added in v0.4.0

func (c *ControlBase) Child(id string) ControlI

Child returns the child control with the given id. TODO: This should be a map, both to speed it up, and add the ability to sort it

func (*ControlBase) ChildValidationChanged added in v0.4.0

func (c *ControlBase) ChildValidationChanged()

ChildValidationChanged is sent by the framework when a child control's validation message has changed. Parent controls can use this to change messages or attributes in response.

func (*ControlBase) Children added in v0.4.0

func (c *ControlBase) Children() []ControlI

Children returns the child controls of the control.

func (*ControlBase) Cleanup added in v0.4.0

func (c *ControlBase) Cleanup()

Cleanup is called by the framework when a control is being removed from the page cache. It is an opportunity to remove any potential circular references in your controls that would prevent the garbage collector from removing the control from memory. In particular, references to parent objects would be a problem.

func (*ControlBase) DataConnector added in v0.4.0

func (c *ControlBase) DataConnector() DataConnector

DataConnector returns the control's data connector if one has been set.

func (*ControlBase) Deserialize added in v0.4.0

func (c *ControlBase) Deserialize(d Decoder)

Deserialize is called by GobDecode to deserialize the control. It is overridable, and control implementations should call this first before calling their own version. However, after deserialization, the control will not be ready for use, since its parent, form or child controls still need to be deserialized. The Decoded function should be called to fix up the necessary internal pointers.

func (*ControlBase) DoAction added in v0.23.0

func (c *ControlBase) DoAction(ctx context.Context, a action.Params)

DoAction is called by the framework in response to a action.Server or action.Ajax action. Forms and controls should implement this method to handle the action. Typically, the Action function will first look at the id to know how to handle it.

func (*ControlBase) DoPrivateAction added in v0.23.0

func (c *ControlBase) DoPrivateAction(ctx context.Context, a action.Params)

DoPrivateAction processes actions that a control sets up for itself, and that it does not want to give the opportunity for users of the control to manipulate or remove those actions. Generally, private actions should call their embedded DoPrivateAction method too.

func (*ControlBase) Draw added in v0.4.0

func (c *ControlBase) Draw(ctx context.Context, w io.Writer)

Draw renders the control structure into the given buffer.

func (*ControlBase) DrawAjax added in v0.4.0

func (c *ControlBase) DrawAjax(ctx context.Context, response *Response)

DrawAjax will be called by the framework during an Ajax rendering of the ControlBase. Every ControlBase gets called. Each ControlBase is responsible for rendering itself. Some objects automatically render their child objects, and some don't, so we detect whether the parent is being rendered, and assume the parent is taking care of rendering for us if so.

Override if you want more control over ajax drawing, like if you detect parts of your control that have changed and then want to draw only those parts. This will get called on every control on every ajax draw request. It is up to you to test the blnRendered flag of the control to know whether the control was already rendered by a parent control before drawing here.

func (*ControlBase) DrawChildren added in v0.4.0

func (c *ControlBase) DrawChildren(ctx context.Context, w io.Writer)

DrawChildren renders the child controls that have not yet been drawn into the buffer.

func (*ControlBase) DrawInnerHtml added in v0.4.0

func (c *ControlBase) DrawInnerHtml(ctx context.Context, w io.Writer)

DrawInnerHtml is used by the framework to draw just the inner html of the control, if the control is not a self terminating (void) control. Sub-controls can override this.

func (*ControlBase) DrawPostRender added in v0.23.0

func (c *ControlBase) DrawPostRender(ctx context.Context, w io.Writer)

DrawPostRender is called by the framework at the end of drawing, and is the place where controls do any post-drawing cleanup needed.

func (*ControlBase) DrawPreRender added in v0.23.0

func (c *ControlBase) DrawPreRender(ctx context.Context, w io.Writer)

DrawPreRender is called by the framework to notify the control that it is about to be drawn. If you override it, be sure to also call this parent function as well.

func (*ControlBase) DrawTag added in v0.4.0

func (c *ControlBase) DrawTag(ctx context.Context, w io.Writer)

DrawTag is responsible for drawing the ControlBase's tag itself. ControlBase implementations can override this to draw the tag in a different way, or draw more than one tag if drawing a compound control.

func (*ControlBase) DrawTemplate added in v0.4.0

func (c *ControlBase) DrawTemplate(ctx context.Context, w io.Writer) (err error)

DrawTemplate is used by the framework to draw the Control using a template. Controls that use templates should use this function signature for the template. That will override this one, and we will then detect that the template was drawn. Otherwise, we detect that no template was defined, and it will move on to drawing the controls without a template, or just the text if text is defined.

func (*ControlBase) DrawText added in v0.4.0

func (c *ControlBase) DrawText(ctx context.Context, w io.Writer)

DrawText renders the text of the control, escaping if needed.

func (*ControlBase) DrawingAttributes added in v0.4.0

func (c *ControlBase) DrawingAttributes(ctx context.Context) html5tag.Attributes

DrawingAttributes is called by the framework just before drawing a control, and should return a set of attributes that should override those set by the user. This allows controls to set attributes that should take precedence over other attributes, and that are critical to drawing the tag of the control. This function is designed to only be called by ControlBase implementations.

func (*ControlBase) Event added in v0.23.0

func (c *ControlBase) Event(eventName string) *event.Event

Event returns the event associated with the eventName, which corresponds to the javascript trigger name.

func (*ControlBase) ExecuteWidgetFunction added in v0.4.0

func (c *ControlBase) ExecuteWidgetFunction(command string, params ...interface{})

ExecuteWidgetFunction will execute the given JavaScript function on the matching client object, with the given parameters. The function is a widget function of the goradd widget wrapper or similar type of object.

func (*ControlBase) FireTestMarker added in v0.12.0

func (c *ControlBase) FireTestMarker(marker string)

FireTestMarker sends a marker signal to the browser test runner. You would normally send this from some place in your application during testing if you want to wait until your app has gotten to that spot. Call WaitMarker on the test form to wait for the marker.

func (*ControlBase) GT added in v0.4.0

func (c *ControlBase) GT(message string) string

GT translates strings using the Goradd dictionary.

func (*ControlBase) GetActionScripts added in v0.4.0

func (c *ControlBase) GetActionScripts(r *Response)

GetActionScripts is an internal function called during drawing to gather all the event related scripts attached to the control and send them to the response.

func (*ControlBase) HasAttribute added in v0.4.0

func (c *ControlBase) HasAttribute(name string) bool

HasAttribute returns true if the control has the indicated custom attribute defined.

func (*ControlBase) HasClass added in v0.10.0

func (c *ControlBase) HasClass(class string) bool

HasClass returns true if the class has been assigned to the control from the GO side. We do not currently detect class changes done in javascript.

func (*ControlBase) ID added in v0.4.0

func (c *ControlBase) ID() string

ID returns the id assigned to the control. If you do not provide an ID when the control is created, the framework will give the control a unique id.

func (*ControlBase) Init added in v0.4.0

func (c *ControlBase) Init(parent ControlI, id string)

Init is used by ControlBase implementations to initialize the standard control structure. You would only call this if you are subclassing one of the standard controls. ControlBase implementations should call this immediately after a control is created. The ControlBase subclasses should have their own Init function that calls this superclass function. This Init function sets up a parent-child relationship with the given parent control.

The id given will be used as the id in the corresponding HTML tag, and should be unique on the page. Leave blank for the system to create a unique id for you. A nil parent is for top level controls, primarily Forms.

func (*ControlBase) IsDisabled added in v0.4.0

func (c *ControlBase) IsDisabled() bool

IsDisabled returns true if the disabled attribute is true.

func (*ControlBase) IsDisplayed added in v0.4.0

func (c *ControlBase) IsDisplayed() bool

IsDisplayed returns true if the control will be displayed.

func (*ControlBase) IsOnPage added in v0.4.0

func (c *ControlBase) IsOnPage() bool

func (*ControlBase) IsRendering added in v0.4.0

func (c *ControlBase) IsRendering() bool

IsRendering returns true if we are in the process of rendering the control.

func (*ControlBase) IsRequired added in v0.4.0

func (c *ControlBase) IsRequired() bool

IsRequired returns true if the control requires a value to be set in order to pass validation.

func (*ControlBase) IsVisible added in v0.4.0

func (c *ControlBase) IsVisible() bool

IsVisible returns whether the control will be drawn.

func (*ControlBase) MarshalJSON added in v0.4.0

func (c *ControlBase) MarshalJSON() (data []byte, err error)

func (*ControlBase) MarshalState added in v0.4.0

func (c *ControlBase) MarshalState(m SavedState)

MarshalState is a helper function for control implementations to save their state, so that if the form is reloaded, the value that the user entered will not be lost. Implementing controls should add items to the given map. Note that the control id is used as a key for the state, so that if you are dynamically adding controls, you should make sure you give a specific, non-changing control id to the control, or the state may be lost.

func (*ControlBase) MergeAttributes added in v0.4.0

func (c *ControlBase) MergeAttributes(a html5tag.Attributes) ControlI

MergeAttributes will merge the given attributes into the control's attributes.

func (*ControlBase) MockFormValue added in v0.4.0

func (c *ControlBase) MockFormValue(value string) bool

MockFormValue will mock the process of getting a form value from an HTTP response for testing purposes. This includes calling UpdateFormValues and Validate on the control. It returns the result of the Validate function.

func (*ControlBase) NeedsRefresh added in v0.12.0

func (c *ControlBase) NeedsRefresh() bool

NeedsRefresh returns true if the control needs to be completely redrawn. Generally you control this by calling Refresh(), but subclasses can implement other ways of detecting this.

func (*ControlBase) Off added in v0.4.0

func (c *ControlBase) Off()

Off removes all event handlers from the control

func (*ControlBase) On added in v0.4.0

On adds an event listener to the control that will trigger the given actions. To have a single event fire multiple actions, use action.Group() to combine the actions into one.

func (*ControlBase) Page added in v0.4.0

func (c *ControlBase) Page() *Page

Page returns the page object associated with the control.

func (*ControlBase) Parent added in v0.4.0

func (c *ControlBase) Parent() ControlI

Parent returns the parent control of the control. All controls have a parent, except the Form control.

func (*ControlBase) ParentForm added in v0.4.0

func (c *ControlBase) ParentForm() FormI

ParentForm returns the form object that encloses this control.

func (*ControlBase) ProcessAttributeString added in v0.7.1

func (c *ControlBase) ProcessAttributeString(s string) ControlI

ProcessAttributeString is used by the drawing template to let you set attributes in the draw tag. Attributes are of the form `name="value"`.

func (*ControlBase) PutCustomScript added in v0.4.0

func (c *ControlBase) PutCustomScript(ctx context.Context, response *Response)

PutCustomScript is called by the framework to ask the control to inject any javascript it needs into the form. In particular, this is the place where Controls add javascript that transforms the html into a custom javascript control. A ControlBase implementation does this by calling functions on the response object.

func (*ControlBase) RangeAllChildren added in v0.4.0

func (c *ControlBase) RangeAllChildren(f func(child ControlI))

RangeAllChildren recursively calls the given function on every child control and subcontrol. It calls the function on the child controls of each control first, and then on the control itself.

func (*ControlBase) RangeSelfAndAllChildren added in v0.4.0

func (c *ControlBase) RangeSelfAndAllChildren(f func(ctrl ControlI))

RangeSelfAndAllChildren recursively calls the given function on this control and every child control and subcontrol. It calls the function on the child controls of each control first, and then on the control itself.

func (*ControlBase) Refresh added in v0.4.0

func (c *ControlBase) Refresh()

Refresh will force the control to be completely redrawn on the next update.

func (*ControlBase) RefreshData added in v0.4.0

func (c *ControlBase) RefreshData(data interface{})

RefreshData is called by forms to tell controls to set their appearance based on the data provided. The default calls the data connector to do this.

func (*ControlBase) Remove added in v0.4.0

func (c *ControlBase) Remove()

Remove removes the current control from its parent. After this is done, the control and all its child items will not be part of the drawn form, but the child items will still be accessible through the control itself.

func (*ControlBase) RemoveChild added in v0.4.0

func (c *ControlBase) RemoveChild(id string)

RemoveChild removes the given child control from both the control and the form.

func (*ControlBase) RemoveChildren added in v0.4.0

func (c *ControlBase) RemoveChildren()

RemoveChildren removes all the child controls from this control and the form so that the memory manager can delete them.

func (*ControlBase) RemoveClass added in v0.4.0

func (c *ControlBase) RemoveClass(class string) ControlI

RemoveClass will remove the named class from the control.

func (*ControlBase) RemoveClassesWithPrefix added in v0.4.0

func (c *ControlBase) RemoveClassesWithPrefix(prefix string)

RemoveClassesWithPrefix will remove the classes on a control that start with the given string. Some CSS frameworks use prefixes to as a kind of namespace for their class tags, and this can make it easier to remove a group of classes with this kind of prefix.

func (*ControlBase) RenderAutoControls added in v0.4.0

func (c *ControlBase) RenderAutoControls(ctx context.Context, w io.Writer)

RenderAutoControls is an internal function to draw controls marked to autoRender. These are generally used for hidden controls that can be shown without impacting layout, or that are scripts only. ControlBase implementations that need to put these controls in particular locations on the form can override this.

func (*ControlBase) ResetValidation added in v0.7.0

func (c *ControlBase) ResetValidation()

func (*ControlBase) Restore added in v0.4.0

func (c *ControlBase) Restore()

Restore is called by the framework for control implemenatations. It is called after the control has been deserialized. It notifies the control tree so that it can restore internal pointers if needed.

func (*ControlBase) SaveState added in v0.4.0

func (c *ControlBase) SaveState(ctx context.Context, saveIt bool)

SaveState sets whether the control should save its value and other state information so that if the form is redrawn, the value can be restored.

Call this during control initialization to cause the control to remember what it is set to, so that if the user returns to the page, it will keep its value. This function is also responsible for restoring the previously saved state of the control, so call this only after you have set the default state of a control during creation or initialization.

func (*ControlBase) Serialize added in v0.4.0

func (c *ControlBase) Serialize(e Encoder)

Serialize is used by the framework to serialize a control to be saved in the pagestate. It is overridable, and control implementations should call this function first before their own serializer.

func (*ControlBase) SetActionValue added in v0.4.0

func (c *ControlBase) SetActionValue(v interface{}) ControlI

SetActionValue sets a value that is provided to actions when they are triggered. The value can be a static value or one of the javascript.* objects that can dynamically generate values. The value is then sent back to the Action function after the action is triggered as the ControlActionValue in the action.Params struct.

func (*ControlBase) SetAttribute added in v0.4.0

func (c *ControlBase) SetAttribute(name string, val interface{}) ControlI

SetAttribute sets an HTML attribute of the control. You can manually set almost any attribute, but be careful not to set the id attribute, or any attribute that is managed by the control itself. If you are setting a data-* attribute, use [SetDataAttribute] instead. If you are adding a class to the control, use [AddClass].

func (*ControlBase) SetBlockParentValidation added in v0.4.0

func (c *ControlBase) SetBlockParentValidation(block bool)

SetBlockParentValidation will prevent a parent from validating this control. This is generally useful for panels and other containers of controls that wish to have their own validation scheme. Dialogs in particular need this since they act as a separate form, even though technically they are included in a form.

func (*ControlBase) SetDataAttribute added in v0.4.0

func (c *ControlBase) SetDataAttribute(name string, val interface{})

SetDataAttribute will set a data-* attribute. The name should be camelCase, without "data" in the name. For example:

SetDataAttribute("myVal", 5)

will result in the "data-my-val=5" attribute appearing in the HTML, which will be accessible from javascript using .data("myVal").

func (*ControlBase) SetDataConnector added in v0.4.0

func (c *ControlBase) SetDataConnector(d DataConnector) ControlI

SetDataConnector sets the data connector. The connector must be registered with Gob to be serializable.

func (*ControlBase) SetDisabled added in v0.4.0

func (c *ControlBase) SetDisabled(d bool)

SetDisabled will set the "disabled" attribute of the control.

func (*ControlBase) SetDisplay added in v0.4.0

func (c *ControlBase) SetDisplay(d string) ControlI

SetDisplay sets the "display" property of the style attribute of the html control to the given value. Also consider using SetVisible. If you use SetDisplay to hide a control, the control will still be rendered in html, but the browser will not show it.

func (*ControlBase) SetHasNoSpace added in v0.4.0

func (c *ControlBase) SetHasNoSpace(v bool) ControlI

SetHasNoSpace tells the control to draw its inner html with no space around it. This should generally only be called by control implementations. If this is not set, spaces might be added to make the HTML more readable, which can affect some html control types.

func (*ControlBase) SetHeightStyle added in v0.4.0

func (c *ControlBase) SetHeightStyle(h interface{}) ControlI

SetHeightStyle sets the height style property

func (*ControlBase) SetIsRequired added in v0.4.0

func (c *ControlBase) SetIsRequired(r bool) ControlI

SetIsRequired will set whether the control requires a value from the user. Setting it to true will cause the ControlBase to check this during validation, and show an appropriate error message if the user did not enter a value.

func (*ControlBase) SetParent added in v0.4.0

func (c *ControlBase) SetParent(newParent ControlI)

SetParent sets the parent of the control. Use this primarily if you are responding to some kind of user interface that will move a child ControlBase from one parent ControlBase to another.

func (*ControlBase) SetShouldAutoRender added in v0.4.0

func (c *ControlBase) SetShouldAutoRender(r bool)

SetShouldAutoRender sets whether this control will automatically render. AutoRendered controls are drawn by the form automatically, after all other controls are drawn, if the control was not drawn in some other way. An example of an auto-rendered control would be a dialog box that starts out hidden, but then is shown by some user response. Such controls are normally shown by javascript, and are absolutely positioned so that they do not affect the layout of the rest of the form.

func (*ControlBase) SetStyle added in v0.4.0

func (c *ControlBase) SetStyle(name string, value string) ControlI

SetStyle sets a particular property of the style attribute on the control.

func (*ControlBase) SetStyles added in v0.4.0

func (c *ControlBase) SetStyles(s html5tag.Style)

SetStyles sets the style attribute of the control to the given values.

func (*ControlBase) SetText added in v0.4.0

func (c *ControlBase) SetText(t string) ControlI

SetText sets the text of the control. Not all controls use this value.

func (*ControlBase) SetTextIsHtml added in v0.4.0

func (c *ControlBase) SetTextIsHtml(h bool) ControlI

SetTextIsHtml to true to turn off html escaping of the text output.

func (*ControlBase) SetValidationError added in v0.4.0

func (c *ControlBase) SetValidationError(e string)

SetValidationError sets the validation error to the given string. It will also handle setting the wrapper class to indicate an error. Override if you have a different way of handling errors.

func (*ControlBase) SetValidationTargets added in v0.4.0

func (c *ControlBase) SetValidationTargets(controlIDs ...string)

SetValidationTargets specifies which controls to validate, in conjunction with the ValidationType setting, giving you very fine-grained control over validation. The default is to use just this control as the target.

func (*ControlBase) SetValidationType added in v0.4.0

func (c *ControlBase) SetValidationType(typ event.ValidationType) ControlI

SetValidationType specifies how this control validates other controls. Typically, its either ValidateNone or ValidateForm.

  • ValidateForm will validate all the controls on the form.
  • ValidateSiblingsAndChildren will validate the immediate siblings of the target controls and their children
  • ValidateSiblingsOnly will validate only the siblings of the target controls
  • ValidateTargetsOnly will validate only the specified target controls

func (*ControlBase) SetVisible added in v0.4.0

func (c *ControlBase) SetVisible(v bool)

SetVisible controls whether the ControlBase will be drawn. Controls that are not visible are not rendered in html, but rather a hidden stub is rendered as a placeholder in case the control is made visible again.

func (*ControlBase) SetWidthStyle added in v0.4.0

func (c *ControlBase) SetWidthStyle(w interface{}) ControlI

SetWidthStyle sets the width style property

func (*ControlBase) SetWillBeValidated added in v0.4.0

func (c *ControlBase) SetWillBeValidated(v bool)

SetWillBeValidated indicates to the wrapper whether to save a spot for a validation message or not.

func (*ControlBase) ShouldAutoRender added in v0.4.0

func (c *ControlBase) ShouldAutoRender() bool

ShouldAutoRender returns true if the control is set up to auto-render.

func (*ControlBase) T added in v0.4.0

func (c *ControlBase) T(message string, params ...interface{}) string

T sends strings to the translator for translation, and returns the translated string. The language is taken from the session. See the i18n package for more info on that mechanism. Additionally, you can add an i18n.ID() call to add an id to the translation to disambiguate it from similar strings, and you can add an i18n.Comment() call to add an extracted comment for the translators. The message string should be a literal string and not a variable, so that an extractor can extract it from your source to put it into a translation file. This version passes the literal string.

Examples:

textbox.T("I have %d things", count, i18n.Comment("This will need multiple translations based on the count value"));
textbox.SetText(textbox.T("S", i18n.ID("South")));

func (*ControlBase) TPrintf added in v0.4.0

func (c *ControlBase) TPrintf(message string, params ...interface{}) string

TPrintf is like T(), but works like Sprintf, returning the translated string, but sending the arguments to the message as if the message was a Sprintf format string. The go/text extractor has code that can do interesting things with this kind of string.

func (*ControlBase) Text added in v0.4.0

func (c *ControlBase) Text() string

Text returns the text of the control.

func (*ControlBase) TextIsLabel added in v0.4.0

func (c *ControlBase) TextIsLabel() bool

TextIsLabel is used by the drawing routines to determine if the control's text should be wrapped with a label tag. This is normally used by checkboxes and radio buttons that use the label tag in a special way.

func (*ControlBase) UnmarshalJSON added in v0.4.0

func (c *ControlBase) UnmarshalJSON(data []byte) (err error)

func (*ControlBase) UnmarshalState added in v0.4.0

func (c *ControlBase) UnmarshalState(m SavedState)

UnmarshalState is a helper function for control implementations to retrieve their state from state storage. To implement it, a control should read the data out of the given map. If needed, implement your own version checking scheme. The given map will be guaranteed to have been written out by the same kind of control as the one reading it. Control implementations should be sure to call the superclass version too.

func (*ControlBase) UpdateData added in v0.4.0

func (c *ControlBase) UpdateData(data interface{})

UpdateData is called by forms to tell controls to put the control value into the provided data object. The default calls the data connector to do this.

func (*ControlBase) UpdateFormValues added in v0.4.0

func (c *ControlBase) UpdateFormValues(ctx context.Context)

UpdateFormValues is used by the framework to cause the control to retrieve its values from the form

func (*ControlBase) Validate added in v0.4.0

func (c *ControlBase) Validate(ctx context.Context) bool

Validate is called by the framework to validate a control, but not the control's children. It is designed to be overridden by ControlBase implementations. Overriding controls should call the parent version before doing their own validation.

func (*ControlBase) ValidationMessage added in v0.4.0

func (c *ControlBase) ValidationMessage() string

ValidationMessage is the currently set validation message that will print with the control. Normally this only gets set when a validation error occurs.

func (*ControlBase) ValidationState added in v0.4.0

func (c *ControlBase) ValidationState() ValidationState

ValidationState returns the current ValidationState value.

func (*ControlBase) ValidationType added in v0.4.0

func (c *ControlBase) ValidationType(e *event.Event) event.ValidationType

ValidationType is an internal function to return the validation type. It allows subclasses to override it.

func (*ControlBase) WasRendered added in v0.4.0

func (c *ControlBase) WasRendered() bool

WasRendered returns true if the control has been rendered.

func (*ControlBase) WatchChannel added in v0.4.0

func (c *ControlBase) WatchChannel(ctx context.Context, channel string)

WatchChannel allows you to specify any channel to watch that will cause the control to redraw.

func (*ControlBase) WatchDbRecord added in v0.4.0

func (c *ControlBase) WatchDbRecord(ctx context.Context, n query.NodeI, pk string)

WatchDbRecord will watch a specific record. Specify a table node to watch all fields in the record, or a column node to watch the changes to a particular field of the table.

func (*ControlBase) WatchDbTables added in v0.4.0

func (c *ControlBase) WatchDbTables(ctx context.Context, nodes ...query.NodeI)

WatchDbTables will add the table nodes to the list of database tables that the control is watching. When data in that table changes, the control is updated. It also adds all the parents of those nodes. For example, WatchDbTables(ctx, node.Project().Manager()) will watch the project table and the person table.

func (*ControlBase) WrapEvent added in v0.4.0

func (c *ControlBase) WrapEvent(eventName string, selector string, eventJs string, options map[string]interface{}) string

WrapEvent is an internal function to allow the control to customize its treatment of event processing.

type ControlI

type ControlI interface {
	ID() string

	DrawI
	DrawTag(context.Context, io.Writer)
	DrawInnerHtml(context.Context, io.Writer)
	DrawTemplate(context.Context, io.Writer) error
	DrawPreRender(context.Context, io.Writer)
	DrawPostRender(context.Context, io.Writer)
	DrawAjax(ctx context.Context, response *Response)
	DrawChildren(ctx context.Context, w io.Writer)
	DrawText(ctx context.Context, w io.Writer)

	Parent() ControlI
	Children() []ControlI
	SetParent(parent ControlI)
	Remove()
	RemoveChild(id string)
	RemoveChildren()
	Page() *Page
	ParentForm() FormI
	Child(string) ControlI
	RangeAllChildren(func(ControlI))
	RangeSelfAndAllChildren(func(ControlI))

	SetAttribute(name string, val interface{}) ControlI
	Attribute(string) string
	HasAttribute(string) bool
	ProcessAttributeString(s string) ControlI
	DrawingAttributes(context.Context) html5tag.Attributes
	AddClass(class string) ControlI
	RemoveClass(class string) ControlI
	HasClass(class string) bool
	SetStyles(html5tag.Style)
	SetStyle(name string, value string) ControlI
	SetWidthStyle(w interface{}) ControlI
	SetHeightStyle(w interface{}) ControlI
	Attributes() html5tag.Attributes
	SetDisplay(d string) ControlI
	SetDisabled(d bool)
	IsDisabled() bool
	SetTextIsHtml(bool) ControlI

	PutCustomScript(ctx context.Context, response *Response)

	TextIsLabel() bool
	Text() string
	SetText(t string) ControlI
	ValidationMessage() string
	SetValidationError(e string)
	ResetValidation()

	WasRendered() bool
	IsRendering() bool
	IsVisible() bool
	SetVisible(bool)
	IsOnPage() bool

	Refresh()
	NeedsRefresh() bool

	DoAction(context.Context, action.Params)
	DoPrivateAction(context.Context, action.Params)
	SetActionValue(interface{}) ControlI
	ActionValue() interface{}
	On(e *event.Event, a action.ActionI) ControlI
	Off()
	WrapEvent(eventName string, selector string, eventJs string, options map[string]interface{}) string
	Event(eventName string) *event.Event

	// UpdateFormValues is used by the framework to cause the control to retrieve its values from the form
	UpdateFormValues(context.Context)

	Validate(ctx context.Context) bool
	ValidationState() ValidationState
	ValidationType(*event.Event) event.ValidationType
	SetValidationType(typ event.ValidationType) ControlI
	ChildValidationChanged()

	// SaveState tells the control whether to save the basic state of the control, so that when the form is reentered, the
	// data in the control will remain the same. This is particularly useful if the control is used as a filter for the
	// contents of another control.
	SaveState(context.Context, bool)
	MarshalState(m SavedState)
	UnmarshalState(m SavedState)

	// GT translates strings using the Goradd dictionary.
	GT(format string) string
	// T translates strings using the application provided dictionary.
	T(message string, params ...interface{}) string
	TPrintf(format string, params ...interface{}) string

	Restore()
	Cleanup()

	SetIsRequired(r bool) ControlI

	Serialize(e Encoder)
	Deserialize(d Decoder)

	ApplyOptions(ctx context.Context, o ControlOptions)
	AddControls(ctx context.Context, creators ...Creator)

	DataConnector() DataConnector
	SetDataConnector(d DataConnector) ControlI
	RefreshData(data interface{})
	UpdateData(data interface{})

	WatchDbTables(ctx context.Context, nodes ...query.NodeI)
	WatchDbRecord(ctx context.Context, n query.NodeI, pk string)
	WatchChannel(ctx context.Context, channel string)
	// contains filtered or unexported methods
}

ControlI is the interface that all controls must support. The functions are implemented by the ControlBase methods. See the ControlBase method implementation for a description of each method.

type ControlOptions added in v0.2.0

type ControlOptions struct {
	// Attributes will set the attributes of the control. Use DataAttributes to set data attributes, Styles to set styles, and Class to set the class
	Attributes html5tag.Attributes
	// DataAttributes will set the data-* attributes of the control.
	DataAttributes DataAttributeMap
	// Styles sets the styles of the control's tag
	Styles html5tag.Style
	// Class sets the class of the control's tag. Prefix a class with "+" to add a class, or "-" to remove a class.
	Class string
	// IsDisabled initializes the control in the disabled state, with a "disabled" attribute
	IsDisabled bool
	// IsRequired is used by the validator. If a value is required, and the control is empty, it will not pass validation.
	IsRequired bool
	// IsHidden initializes this control as hidden. A placeholder will be sent in the html so that when the control is shown through ajax, we will know where to put it.
	IsHidden bool
	// On adds events with actions to the control
	On EventList
	// DataConnector is the ViewModel layer that moves data between the control and an attached model.
	DataConnector DataConnector
	// WatchedDbTables lets you specify database nodes to watch for changes. When a record in the table is altered, added or deleted,
	// this control will automatically redraw. To watch a specific record, call WatchDbRecord when you load the control's data.
	WatchedDbTables []query.NodeI
}

ControlOptions are options common to all controls

type ControlTemplateFunc

type ControlTemplateFunc func(ctx context.Context, control ControlI, w io.Writer) error

ControlTemplateFunc is the type of function control templates should create

type ControlWrapperFunc

type ControlWrapperFunc func(ctx context.Context, control ControlI, ctrl string, w io.Writer) error

ControlWrapperFunc is a template function that specifies how wrappers will draw

type Creator added in v0.2.0

type Creator interface {
	Create(ctx context.Context, parent ControlI) ControlI
}

Creator is the interface all declarative helpers need to implement. It is used to add multiple controls with various settings from a single Go struct.

type DataAttributeMap added in v0.2.0

type DataAttributeMap map[string]interface{}

DataAttributeMap is used by Creators to declare a map of data attributes.

type DataConnector added in v0.2.0

type DataConnector interface {
	// Refresh reads from the model, and puts it into the control
	Refresh(i ControlI, model interface{})
	// Update reads data from the control, and puts it into the model
	Update(i ControlI, model interface{})
}

The DataConnector moves data between the control and the database model. It is a thin view-model controller that can be customized on a per-control basis.

type DataLoader added in v0.2.0

type DataLoader interface {
	Load(ctx context.Context) []interface{}
}

DataLoader is an optional interface that DataConnectors can use if they need to load data from the database to present a choice of items to the user to select from. The Load method will be called whenever the entire control gets redrawn.

type DbError

type DbError struct {
	Error
	// DbStatement is the captured database statement if one caused the error, returned by the db adapter
	DbStatement string
}

DbError represents a database error.

type Decoder

type Decoder interface {
	Decode(v interface{}) error
}

Decoder defines objects that can be decoded from a pagestate. If the object does not implement this, we will look for GobDecode support.

type DrawI

type DrawI interface {
	Draw(context.Context, io.Writer)
}

DrawI is the interface for items that draw into the draw buffer.

type Encoder

type Encoder interface {
	Encode(v interface{}) error
}

Encoder defines objects that can be encoded into a pagestate.

type Error

type Error struct {
	// the error string
	Err error
	// the time the error occurred
	Time time.Time
	// the copied context when the error occurred
	Ctx *Context
	// unwound Stack info
	Stack []StackFrame
}

The error structure, specifically designed to manage panics during request handling

type EventList added in v0.2.0

type EventList []struct {
	Event  *event.Event
	Action action.ActionI
}

EventList is used by Creators to declare a list of event and action pairs. Use action.Group as the Action to assign multiple actions to single event.

type FastPagestateCache added in v0.13.2

type FastPagestateCache struct {
	cache.LruCache
}

FastPagestateCache is an in memory page cache that does no serialization and uses an LRU cache of page objects. Objects that are too old are removed, and if the cache is full, the oldest item(s) will be removed. When a page is updated, it is moved to the top. Whenever an item is set, we could potentially garbage collect. This cache can be used in a production environment if the application is guaranteed to only work on a single machine. If you want scalability, use a serializing page cache that serializes directly to a database that is accessible from all instances of the app.

func NewFastPageCache

func NewFastPageCache(maxEntries int, TTL int64) *FastPagestateCache

NewFastPageCache creates a new FastPagestateCache cache

func (*FastPagestateCache) Get added in v0.13.2

func (o *FastPagestateCache) Get(pageId string) *Page

Get returns the page based on its page id. If not found, will return null.

func (*FastPagestateCache) Has added in v0.13.2

func (o *FastPagestateCache) Has(pageId string) bool

Has tests to see if the given page id is in the page cache, without actually loading the page

func (*FastPagestateCache) NewPageID added in v0.13.2

func (o *FastPagestateCache) NewPageID() string

NewPageID returns a new page id

func (*FastPagestateCache) Set added in v0.13.2

func (o *FastPagestateCache) Set(pageId string, page *Page)

Set puts the page into the page cache and updates its access time, pushing it to the end of the removal queue. Page must already be assigned a state ID. Use NewPageId to do that.

type FormBase added in v0.4.0

type FormBase struct {
	ControlBase
	// contains filtered or unexported fields
}

FormBase is a base for the FormBase struct that is in the control package. Normally, you should not descend your forms from here, but rather from the control.Form struct. It is the basic control structure for the application and also serves as the drawing mechanism for the <form> tag in the html output.

func (*FormBase) AddGoraddFiles added in v0.4.0

func (f *FormBase) AddGoraddFiles()

AddGoraddFiles adds the various goradd files to the form

func (*FormBase) AddHeadTags added in v0.4.0

func (f *FormBase) AddHeadTags()

AddHeadTags is a lifecycle call that happens when a new form is created. This is where you should call AddHtmlHeaderTag or SetTitle on the page to set tags that appear in the <head> tag of the page. Head tags cannot be changed after the page is created.

func (*FormBase) AddJavaScriptFile added in v0.4.0

func (f *FormBase) AddJavaScriptFile(path string, forceHeader bool, attributes html5tag.Attributes)

AddJavaScriptFile registers a JavaScript file such that it will get loaded on the page.

The path is either a url, or an internal path to the location of the file in the development environment.

If forceHeader is true, the file will be listed in the header, which you should only do if the file has some preliminary javascript that needs to be executed before the dom loads. You can specify forceHeader and a "defer" attribute to get the effect of loading the javascript in the background. With forceHeader false, the file will be loaded after the dom is loaded, allowing the browser to show the page and then load the javascript in the background, giving the appearance of a more responsive website. If you add the file during an ajax operation, the file will be loaded dynamically by the goradd javascript. Controls generally should call this during the initial creation of the control if the control requires additional javascript to function.

attributes are the attributes that will be included with the script tag, which is useful for things like crossorigin and integrity attributes.

func (*FormBase) AddMasterJavaScriptFile added in v0.4.0

func (f *FormBase) AddMasterJavaScriptFile(url string, attributes []string, files []string)

AddMasterJavaScriptFile adds a javascript file that is a concatenation of other javascript files the system uses. This allows you to concatenate and minimize all the javascript files you are using without worrying about libraries and controls that are adding the individual files through the AddJavaScriptFile function

func (*FormBase) AddRelatedFiles added in v0.4.0

func (f *FormBase) AddRelatedFiles()

AddRelatedFiles adds related javascript and style sheet files. This is the default to get the minimum goradd installation working., The order is important, so if you override this, be sure these files get loaded before other files.

func (*FormBase) AddStyleSheetFile added in v0.4.0

func (f *FormBase) AddStyleSheetFile(path string, attributes html5tag.Attributes)

AddStyleSheetFile registers a StyleSheet file such that it will get loaded on the page. The file will be loaded on the page at initial draw in the header, or will be inserted into the file if the page is already drawn. The path is either a url to an external resource, or a local directory to a resource on disk. Paths must be registered with RegisterAssetDirectory, and will be served from their local location in a development environment, but from the corresponding registered path when deployed.

attributes are the attributes that will be included with the link tag, which is useful for things like crossorigin and integrity attributes.

To control the cache-control settings on the file, you should call SetCacheControl.

func (*FormBase) ChangeLocation added in v0.4.0

func (f *FormBase) ChangeLocation(url string)

ChangeLocation will redirect the browser to a new URL.

It does this AFTER processing the return values sent to the browser. Generally you should use this to redirect the browser since you may have some data that needs to be processed first. The exception is if you are responding to some kind of security concern where you only want to send back an HTML redirect without revealing any goradd information, in which case you should use the http.Redirect function.

func (*FormBase) CreateControls added in v0.11.0

func (f *FormBase) CreateControls(ctx context.Context)

CreateControls is a lifecycle function that gets called whenever a page is created. It happens after the Run call. This is the place to add controls to the form

func (*FormBase) Deserialize added in v0.4.0

func (f *FormBase) Deserialize(d Decoder)

func (*FormBase) DisplayAlert added in v0.4.0

func (f *FormBase) DisplayAlert(ctx context.Context, msg string)

DisplayAlert will display a javascript alert with the given message.

func (*FormBase) Draw added in v0.4.0

func (f *FormBase) Draw(ctx context.Context, w io.Writer)

Draw renders the form. Even though forms are technically controls, we use a custom drawing routine for performance reasons and for control.

func (*FormBase) DrawHeaderTags added in v0.4.0

func (f *FormBase) DrawHeaderTags(ctx context.Context, w io.Writer)

DrawHeaderTags is called by the page drawing routine to draw its header tags If you override this, be sure to call this version too

func (*FormBase) DrawPreRender added in v0.23.0

func (f *FormBase) DrawPreRender(ctx context.Context, w io.Writer)

PreRender performs setup operations just before drawing.

func (*FormBase) DrawingAttributes added in v0.4.0

func (f *FormBase) DrawingAttributes(ctx context.Context) html5tag.Attributes

DrawingAttributes returns the attributes to add to the form tag.

func (*FormBase) Exit added in v0.4.0

func (f *FormBase) Exit(ctx context.Context, err error)

Exit is a lifecycle function that gets called after the form is processed, just before control is returned to the client. err will be set if an error response was detected.

func (*FormBase) Init added in v0.4.0

func (f *FormBase) Init(_ context.Context, id string)

Init initializes the form control. Note that ctx might be nil if we are unit testing.

func (*FormBase) LoadControls added in v0.4.0

func (f *FormBase) LoadControls(ctx context.Context)

LoadControls is a lifecycle call that happens after a form is first created. It is the place to initialize the value of the controls in the form based on variables sent to the form or session variables.

func (*FormBase) PageDrawingFunction added in v0.4.0

func (f *FormBase) PageDrawingFunction() PageDrawFunc

PageDrawingFunction returns the function used to draw the page object. If you want a custom drawing function for your page, implement this function in your form override.

func (*FormBase) PopLocation added in v0.4.0

func (f *FormBase) PopLocation(ctx context.Context, fallback string)

PopLocation pops the most recent location off of the location stack and goes to that location. It will go to the fallback url if there is nothing on the stack

func (*FormBase) PushLocation added in v0.4.0

func (f *FormBase) PushLocation(ctx context.Context)

PushLocation pushes the URL that got us to the current page on to the location stack.

func (*FormBase) Refresh added in v0.4.0

func (f *FormBase) Refresh()

func (*FormBase) Response added in v0.4.0

func (f *FormBase) Response() *Response

Response returns the form's response object that you can use to queue up javascript commands to the browser to be sent on the next ajax or server request

func (*FormBase) Run added in v0.4.0

func (f *FormBase) Run(ctx context.Context)

Run is a lifecycle function that gets called whenever a page is run, either by a whole page load, or an ajax call. Its a good place to validate that the current user should have access to the information on the page. You should panic on any errors.

func (*FormBase) Serialize added in v0.4.0

func (f *FormBase) Serialize(e Encoder)

type FormCreationFunction

type FormCreationFunction func(context.Context) FormI

type FormI

type FormI interface {
	ControlI
	// Init initializes the base structures of the form. Do this before adding controls to the form.
	// Note that this signature is different from that of the Init function in FormBase.
	Init(ctx context.Context, id string)
	PageDrawingFunction() PageDrawFunc

	AddHeadTags()
	DrawHeaderTags(ctx context.Context, w io.Writer)
	Response() *Response

	AddRelatedFiles()
	AddStyleSheetFile(path string, attributes html5tag.Attributes)
	AddJavaScriptFile(path string, forceHeader bool, attributes html5tag.Attributes)
	DisplayAlert(ctx context.Context, msg string)
	ChangeLocation(url string)
	PushLocation(ctx context.Context)
	PopLocation(ctx context.Context, fallback string)

	// Lifecycle calls
	Run(ctx context.Context)
	CreateControls(ctx context.Context)
	LoadControls(ctx context.Context)
	Exit(ctx context.Context, err error)
	// contains filtered or unexported methods
}

type FrameworkError

type FrameworkError struct {
	Err      int
	Location string
	Message  string // optional message
}

FrameworkError is an expected error that is part of the framework. Usually you would respond to the error by displaying a message to the user, but not always.

func NewFrameworkError

func NewFrameworkError(err int) FrameworkError

NewFrameworkError creates a new FrameworkError

func (FrameworkError) Error

func (e FrameworkError) Error() string

Error returns the error string

func (FrameworkError) HttpError added in v0.13.8

func (e FrameworkError) HttpError() int

HttpError returns the corresponding http error

func (FrameworkError) SetMessage added in v0.13.8

func (e FrameworkError) SetMessage(msg string) FrameworkError

type GobDeserializer

type GobDeserializer struct {
	*gob.Decoder
}

func (GobDeserializer) Decode

func (e GobDeserializer) Decode(v interface{}) (err error)

type GobPageEncoder

type GobPageEncoder struct {
}

func (GobPageEncoder) NewDecoder

func (e GobPageEncoder) NewDecoder(b *bytes.Buffer) Decoder

func (GobPageEncoder) NewEncoder

func (e GobPageEncoder) NewEncoder(b *bytes.Buffer) Encoder

type GobSerializer

type GobSerializer struct {
	*gob.Encoder
}

func (GobSerializer) Encode

func (e GobSerializer) Encode(v interface{}) (err error)

type HttpContext

type HttpContext struct {
	// Request is the original http.Request object
	Request *http.Request
	// URL is the url being queried
	URL *url.URL

	// Host is the host value extracted from the request
	Host string
	// RemoteAddr is the ip address of the client
	RemoteAddr string
	// Referrer is the referring url, if there is one and it is included in the request. In other words, if a link was
	// clicked to get here, it would be the URL of the page that had the link
	Referrer string
	// Cookies are the cookies coming from the client, mapped by name
	Cookies map[string]*http.Cookie
	// Files are the files being uploaded, if this is a file upload. This currently only works with Server calls
	// in response to a file upload control.
	Files map[string][]*multipart.FileHeader
	// Header is the http header coming from the client.
	Header http.Header
	// contains filtered or unexported fields
}

HttpContext contains typical things we can extract from an http request.

type MockForm added in v0.19.0

type MockForm struct {
	FormBase
}

func NewMockForm added in v0.19.0

func NewMockForm() *MockForm

NewMockForm creates a form that should be used as a parent of a control when unit testing the control.

func (*MockForm) AddRelatedFiles added in v0.19.0

func (f *MockForm) AddRelatedFiles()

type NoErr

type NoErr struct {
}

NoErr represents no error. A request starts with this.

func (*NoErr) Error

func (e *NoErr) Error() string

type Page

type Page struct {
	// BodyAttributes contains the attributes that will be output with the body tag. It should be set before the
	// form draws, like in the AddHeadTags function.
	BodyAttributes string
	// contains filtered or unexported fields
}

The Page object is the top level drawing object, and is essentially a wrapper for the form. The Page draws the html, head and body tags, and includes the one Form object on the page. The page also maintains a record of all the controls included on the form.

func (*Page) AddHtmlHeaderTag

func (p *Page) AddHtmlHeaderTag(t html5tag.VoidTag)

AddHtmlHeaderTag adds the given tag to the head section of the page.

func (*Page) Cleanup added in v0.2.0

func (p *Page) Cleanup()

Cleanup is called by the page cache when the page is removed from memory.

func (*Page) Draw

func (p *Page) Draw(ctx context.Context, w io.Writer)

Draw draws the page.

func (*Page) DrawAjax

func (p *Page) DrawAjax(ctx context.Context, w io.Writer)

DrawAjax renders the page during an ajax call. Since the page itself is already rendered, it simply hands off this responsibility to the form.

func (*Page) DrawHeaderTags

func (p *Page) DrawHeaderTags(ctx context.Context, w io.Writer)

DrawHeaderTags draws all the inner html for the head tag

func (*Page) Form

func (p *Page) Form() FormI

Returns the form for the page

func (*Page) GenerateControlID

func (p *Page) GenerateControlID(id string) string

GenerateControlID generates unique control ids. If you want to do your own id generation, or modifying of given ids, implement that in an override to the control.Init function. The given id is one that the user supplies. User provided ids and generated ids can be further munged by providing an id prefix through SetControlIdPrefix().

func (*Page) GetControl

func (p *Page) GetControl(id string) ControlI

GetControl returns the control with the given id. If not found, it panics. Use HasControl to check for existence.

func (*Page) HasControl added in v0.2.0

func (p *Page) HasControl(id string) bool

func (*Page) HasMetaTag added in v0.7.0

func (p *Page) HasMetaTag(name string) bool

func (*Page) Init

func (p *Page) Init()

Init initializes the page. Should be called by a form just after creating Page.

func (*Page) LanguageCode

func (p *Page) LanguageCode() string

LanguageCode returns the language code that will be put in the lang attribute of the html tag. It is taken from the i18n package.

func (*Page) MarshalBinary added in v0.3.0

func (p *Page) MarshalBinary() (data []byte, err error)

MarshalBinary is called by the framework to serialize the page state.

func (*Page) MarshalJSON

func (p *Page) MarshalJSON() (data []byte, err error)

func (*Page) Restore

func (p *Page) Restore()

Restore is called immediately after the page has been deserialized, to fix up decoded controls.

func (*Page) SetControlIdPrefix

func (p *Page) SetControlIdPrefix(prefix string) *Page

SetControlIdPrefix sets the prefix for control ids. Some javascript frameworks (i.e. jQueryMobile) require that control ids be unique across the application, vs just in the page, because they create internal caches of control ids. This allows you to set a per page prefix that will be added to all control ids to make them unique across the whole application. However, its up to you to make sure the names are unique per page.

func (*Page) SetTitle

func (p *Page) SetTitle(title string)

Call SetTitle to set the content of the <title> tag to be output in the head of the page.

func (*Page) StateID

func (p *Page) StateID() string

StateID returns the page state id. This is output by the form so that we can recover the saved state of the page each time we call into the application.

func (*Page) Title

func (p *Page) Title() string

Title returns the content of the <title> tag that will be output in the head of the page.

func (*Page) UnmarshalBinary added in v0.3.0

func (p *Page) UnmarshalBinary(data []byte) (err error)

func (*Page) UnmarshalJSON

func (p *Page) UnmarshalJSON(data []byte) (err error)

type PageDrawFunc

type PageDrawFunc func(context.Context, *Page, io.Writer) error

PageDrawFunc is the type of the page drawing function. This is implemented by the page drawing template.

type PageEncoderI

type PageEncoderI interface {
	NewEncoder(b *bytes.Buffer) Encoder
	NewDecoder(b *bytes.Buffer) Decoder
}

type PageManager

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

The PageManager is a singleton global that manages the registration and deployment of pages. It acts like a URL router, returning the page that corresponds to a particular URL path. init() functions should be created for each page that associate a function to create a page, with the URL that corresponds to the page, and the ID of the page.

func (*PageManager) IsPage

func (m *PageManager) IsPage(path string) bool

IsPage returns true if the given path has been registered with the page manager.

func (*PageManager) RegisterForm added in v0.5.0

func (m *PageManager) RegisterForm(path string, f FormI, id string)

func (*PageManager) RunPage

func (m *PageManager) RunPage(ctx context.Context, w http2.ResponseWriter, req *http2.Request)

RunPage processes the page and writes the response into the buffer. Any special response headers are returned.

type PageManagerI

type PageManagerI interface {
	RegisterForm(path string, form FormI, formID string)
	RunPage(ctx context.Context, w http2.ResponseWriter, r *http2.Request)
	IsPage(path string) bool
}

func GetPageManager

func GetPageManager() PageManagerI

GetPageManager returns the current page manager.

type PageRenderStatus

type PageRenderStatus int

PageRenderStatus keeps track of whether we are rendering the page or not

const (
	PageIsNotRendering PageRenderStatus = iota // FormBase has started rendering but has not finished
	PageIsRendering
)

Future note. Below is for general information but should NOT be used to synchronize multiple drawing routines. An architecture using channels to synchronize page changes and drawing would be better. For now, except for testing, we should not get in a situation where multiple copies of a form are being used.

type PagestateCacheI added in v0.13.2

type PagestateCacheI interface {
	Set(pageId string, page *Page)
	Get(pageId string) *Page
	NewPageID() string
	Has(pageId string) bool
}

PagestateCacheI is the page cache interface. The PageCache saves and restores pages in between page accesses by the user.

func GetPagestateCache added in v0.13.2

func GetPagestateCache() PagestateCacheI

GetPagestateCache returns the page cache. Used internally by goradd.

type Priority

type Priority int

Priority orders the various responses to an Ajax request so that the framework can control the order they are processed, and not necessarily order the responses in the order they are sent.

const (
	PriorityExclusive Priority = iota
	PriorityHigh
	PriorityStandard
	PriorityLow
	PriorityFinal // TODO: Note that this currently requires a preliminary ajax command, or it will not fire. Should fix that, but its tricky.
)

type RequestMode

type RequestMode int

RequestMode tracks what kind of request we are processing.

const (
	// Server indicates we are calling back to a previously sent form using a standard form post
	Server RequestMode = iota
	// Http indicates this is a first-time request for a page
	Http
	// Ajax indicates we are calling back in to a currently showing form using an ajax request
	Ajax
	// CustomAjax indicates we are calling an entry point from ajax, but not through our js file. This could be used to
	// implement a Rest API at a custom location.
	CustomAjax
	// Cli indicates we are being called from the command line and not through the http server.
	Cli
)

func (RequestMode) String

func (m RequestMode) String() string

String satisfies the Stringer interface and returns a description of the RequestMode

type Response

type Response struct {
	sync.RWMutex // This was inserted here for very rare situations of simultaneous access, like in the test harness.
	// contains filtered or unexported fields
}

Response contains the various commands you can send to the client in response to a goradd event. These commands are packed as JSON (for an Ajax response) or JavaScript (for a Server response), sent to the client, unpacked by JavaScript code in the goradd.js file, and then acted upon.

func NewResponse

func NewResponse() Response

NewResponse creates a new event response.

func (*Response) AddClass added in v0.2.0

func (r *Response) AddClass(id string, class string, priorities ...Priority)

func (*Response) CloseWindow

func (r *Response) CloseWindow()

Call CloseWindow to close the current window.

func (*Response) Deserialize added in v0.3.0

func (r *Response) Deserialize(d Decoder)

Deserialize unpacks the response from the pagestate. Currently the response is only serialized in the testing framework.

func (*Response) ExecuteControlCommand

func (r *Response) ExecuteControlCommand(controlID string, functionName string, args ...interface{})

ExecuteControlCommand executes the named command on the given control. Possible commands are defined by the goradd widget class in the javascript file.

func (*Response) ExecuteJavaScript

func (r *Response) ExecuteJavaScript(js string, priorities ...Priority)

ExecuteJavaScript will execute the given code with the given priority. Note that all javascript code is run in strict mode.

func (*Response) ExecuteJqueryCommand added in v0.2.0

func (r *Response) ExecuteJqueryCommand(controlID string, functionName string, args ...interface{})

ExecuteJqueryCommand executes the named jquery command on the given jquery control.

func (*Response) ExecuteJsFunction

func (r *Response) ExecuteJsFunction(functionName string, args ...interface{})

ExecuteJsFunction calls the given JavaScript function with the given arguments. If the function name has a dot(.) in it, the items preceeding the dot will be considered global objects to call the function on. If the named function just a function label, then the function is called on the window object.

func (*Response) ExecuteSelectorFunction

func (r *Response) ExecuteSelectorFunction(selector string, functionName string, args ...interface{})

ExecuteSelectorFunction calls a goradd function on a group of objects defined by a selector.

func (*Response) GetAjaxResponse added in v0.0.4

func (r *Response) GetAjaxResponse() (buf []byte, err error)

GetAjaxResponse returns the JSON for use by the form ajax response. It will also reset the response

func (*Response) JavaScript

func (r *Response) JavaScript() (script string)

JavaScript renders the Response object as JavaScript that will be inserted into the page sent back to the client in response to a Server action.

func (*Response) RemoveClass added in v0.2.0

func (r *Response) RemoveClass(id string, class string, priorities ...Priority)

func (*Response) Serialize added in v0.3.0

func (r *Response) Serialize(e Encoder)

Serialize encodes the response for the pagestate. Currently, serialization of the response is only used by the testing framework.

func (*Response) SetClass added in v0.2.0

func (r *Response) SetClass(id string, class string, priorities ...Priority)

func (*Response) SetControlAttribute

func (r *Response) SetControlAttribute(id string, attribute string, value string)

SetControlAttribute sets the named html attribute on the control to the given value.

func (*Response) SetControlHtml

func (r *Response) SetControlHtml(id string, html string)

SetControlHtml will cause the given control's html to be completely replaced by the given HTML.

func (*Response) SetControlValue

func (r *Response) SetControlValue(id string, value string)

SetControlValue calls the ".val()" function on the given control, passing it the given value.

func (*Response) SetLocation

func (r *Response) SetLocation(newLocation string)

Call SetLocation to change the url of the browser.

type SavedState added in v0.19.1

type SavedState = maps.MapI[string, any]

SavedState is the container for saving control states so that the control state can be restored when the user comes back to the page.

This is particularly useful for controls that affect the appearance of the page. An example would be a textbox or dropdown that filters a list of items.

type Serializable

type Serializable interface {
	Serialize(e Encoder)
	Deserialize(d Decoder)
}

Serializable defines the interface that allows an object to be encodable using a pre-set encoder. This saves time on memory allocations/deallocations, which might be extensive. Controls are Serializable by default. Other objects that contain controls, or that are not gob.Encoders should implement this as well if they are part of the pagestate.

type SerializedPagestateCache added in v0.13.2

type SerializedPagestateCache struct {
	cache.LruCache
	// contains filtered or unexported fields
}

SerializedPagestateCache is an in memory page cache that does serialization and uses an LRU cache of page objects. Use the serialized page cache during development to ensure that you can eventually move your page cache to a database or a separate machine so that your application is scalable.

This also uses an in memory, non-serialized map to keep the pages in memory so that the testing harness can perform browser-based tests. Essentially this cache should only be used for development purposes and not production.

func NewSerializedPageCache

func NewSerializedPageCache(maxEntries int, TTL int64) *SerializedPagestateCache

func (*SerializedPagestateCache) Get added in v0.13.2

func (o *SerializedPagestateCache) Get(pageId string) *Page

Get returns the page based on its page id. If not found, will return null.

func (*SerializedPagestateCache) Has added in v0.13.2

func (o *SerializedPagestateCache) Has(pageId string) bool

Has returns true if the page with the given pageId is in the cache.

func (*SerializedPagestateCache) NewPageID added in v0.13.2

func (o *SerializedPagestateCache) NewPageID() string

NewPageID returns a new page id

func (*SerializedPagestateCache) Set added in v0.13.2

func (o *SerializedPagestateCache) Set(pageId string, page *Page)

Set puts the page into the page cache, and updates its access time, pushing it to the end of the removal queue Page must already be assigned a state ID. Use NewPageId to do that.

type StackFrame

type StackFrame struct {
	File string
	Line int
	Func string
}

StackFrame holds the file, line and function name in a call chain

type TemplateExecuter

type TemplateExecuter interface {
	Execute(wr io.Writer, data interface{}) error
}

TemplateExecuter is an interface that will work with either text/template or html/template types of templates

func GetTemplate

func GetTemplate(name string) TemplateExecuter

type TestFormI added in v0.3.0

type TestFormI interface {
	NoSerialize() bool
}

The TestFormI interface is used by our test harness to prevent the serialization of the test form.

type ValidationState

type ValidationState int

ValidationState is used internally by the framework to determine how the control's wrapper handles drawing validation error messages. Different wrappers use it to set classes or attributes of the error message or the overall control.

const (
	// ValidationWaiting is the default for controls that accept validation. It means that the control expects to be validated,
	// but has not yet been validated. Wrappers should save a spot for the error message of this control so that if
	// an error appears, it will not change the layout of the form.
	ValidationWaiting ValidationState = iota
	// ValidationNever indicates that the control will never fail validation. Essentially it indicates that the wrapper does not
	// need to save a spot for an error message for this control.
	ValidationNever
	// ValidationValid indicates the control has been validated. This state gets entered if some control on the form has failed validation, but
	// this control passed validation. You can choose to display a special message, or a special color, etc., to
	// indicate to the user that this is not the source of the validation problem, or do nothing.
	ValidationValid
	// ValidationInvalid indicates the control has failed validation, and the wrapper should somehow call that out to the user. The error message
	// should be displayed at a minimum, but likely other things should happen as well, like a special color, and
	// aria attributes should be set.
	ValidationInvalid
)

Directories

Path Synopsis
Package action defines actions that you can trigger using events.
Package action defines actions that you can trigger using events.
Package control contains implementations of standard HTML controls in GoRADD.
Package control contains implementations of standard HTML controls in GoRADD.
button
Package button includes button and button-like controls that are clickable, including things that toggle.
Package button includes button and button-like controls that are clickable, including things that toggle.
dialog
Package dialog contains dialog controls.
Package dialog contains dialog controls.
generator
Package generator contains helper objects to describe controls to the code generator so that they can generate customizable data connectors that associate controls with data in the database.
Package generator contains helper objects to describe controls to the code generator so that they can generate customizable data connectors that associate controls with data in the database.
list
Package list contains list-type controls.
Package list contains list-type controls.
table
Package table implements various table controls.
Package table implements various table controls.
textbox
Package textbox implements textbox-like form controls.
Package textbox implements textbox-like form controls.
Package event contains functions that specify various kinds of javascript events that GoRADD controls respond to.
Package event contains functions that specify various kinds of javascript events that GoRADD controls respond to.
The widget package contains supported composite and special purpose controls that are not part of the html standard
The widget package contains supported composite and special purpose controls that are not part of the html standard

Jump to

Keyboard shortcuts

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