fncmp

package module
v0.3.303 Latest Latest
Warning

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

Go to latest
Published: Mar 15, 2024 License: MIT Imports: 15 Imported by: 4

Documentation

Overview

Package fncmp brings enhanced functionality to the Component interface.

See: kitkitchen.github.io/docs/fncmp

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AddClasses added in v0.3.1

func AddClasses(ctx context.Context, id string, classes ...string)

AddClasses adds classes to an element by ID in the DOM

func EventData added in v0.2.2

func EventData[T any](ctx context.Context) (T, error)

EventData unmarshals event listener data T from the client

func JS added in v0.1.0

func JS(ctx context.Context, fn string, arg any)

JS runs a custom JavaScript function on the client

func MiddleWareFn added in v0.1.0

func MiddleWareFn(h http.HandlerFunc, hf HandleFn) http.HandlerFunc

func OnCacheChange added in v0.3.301

func OnCacheChange[T any](c Cache[T], f func())

OnChange sets a function to be called when the cache is updated

func OnCacheTimeOut added in v0.3.301

func OnCacheTimeOut[T any](c Cache[T], f func())

OnCacheTimeOut sets a function to be called when the cache expires

func RemoveClasses added in v0.3.1

func RemoveClasses(ctx context.Context, id string, classes ...string)

RemoveClasses removes classes from an element by ID in the DOM

func RemoveElement added in v0.3.2

func RemoveElement(ctx context.Context, id string)

Remove element by ID in the DOM

func RemoveTag added in v0.3.2

func RemoveTag(ctx context.Context, tag string)

Remove tag in the DOM

func RenderComponent added in v0.1.1

func RenderComponent(c ...Component) (html string)

RenderComponent renders a component and returns the HTML string

func SetConfig added in v0.3.2

func SetConfig(c *Config)

Types

type Cache added in v0.2.31

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

func NewCache added in v0.3.303

func NewCache[T any](ctx context.Context, key string, initial T) (c Cache[T], err error)

func UseCache added in v0.2.31

func UseCache[T any](ctx context.Context, key string) (c Cache[T], err error)

UseCache takes a generic type, context, and a key and returns a Cache of the type

https://pkg.go.dev/github.com/kitkitchen/fncmp#UseCache

func (*Cache[T]) CreatedAt added in v0.3.2

func (c *Cache[T]) CreatedAt() time.Time

CreatedAt returns the time the cache was created

func (*Cache[T]) Delete added in v0.2.31

func (c *Cache[T]) Delete()

Delete removes the cache from the store

func (*Cache[T]) Expiry added in v0.3.3

func (c *Cache[T]) Expiry() time.Time

Expiry returns expiry time of the cache

func (*Cache[T]) History added in v0.3.301

func (c *Cache[T]) History() (map[string]T, bool)

GetHistory returns the history of the cache

func (*Cache[T]) Record added in v0.3.303

func (c *Cache[T]) Record(r bool)

History returns the history of the cache

func (*Cache[T]) Set added in v0.2.31

func (c *Cache[T]) Set(data T, timeout ...time.Duration) error

Set sets the value of the cache with a timeout

Set timeout to 0 or leave empty for default expiry.

func (*Cache[T]) TimeOut added in v0.3.301

func (c *Cache[T]) TimeOut() time.Duration

func (*Cache[T]) UpdatedAt added in v0.3.2

func (c *Cache[T]) UpdatedAt() time.Time

UpdatedAt returns the time the cache was last updated

func (*Cache[T]) Value added in v0.2.31

func (c *Cache[T]) Value() T

Value returns the current value of the cache

type CacheError added in v0.2.31

type CacheError string
const (
	ErrCacheNotFound  CacheError = "cache not found"
	ErrStoreNotFound  CacheError = "cache store not found; create cache first"
	ErrCacheWrongType CacheError = "cache wrong type"
	ErrCacheExists    CacheError = "cache already exists; delete existing cache first"
)

func (CacheError) Error added in v0.2.31

func (e CacheError) Error() string

type CacheOnFn added in v0.3.301

type CacheOnFn string

type Component

type Component interface {
	Render(ctx context.Context, w io.Writer) error
}

The Component interface is implemented by types that can be rendered

type Config added in v0.1.1

type Config struct {
	Silent       bool          // If true, no logs will be printed
	CacheTimeOut time.Duration // Default cache timeout
	LogLevel     LogLevel
	Logger       *log.Logger
}

func (*Config) Set added in v0.1.1

func (c *Config) Set()

type ContextKey added in v0.1.0

type ContextKey string

ContextKey is used to store values in context esp. for event listeners

const (
	// EventKey is used to store EventListeners in context
	EventKey ContextKey = "event"
	// RequestKey is used to store http.Request in context
	RequestKey ContextKey = "request"
	// ResponseKey is used to store http.ResponseWriter in context
	ErrorKey ContextKey = "error"
)

type Dispatch added in v0.1.0

type Dispatch struct {
	ID         string        `json:"id"`
	Key        string        `json:"key"`
	ConnID     string        `json:"conn_id"`
	HandlerID  string        `json:"handler_id"`
	Action     string        `json:"action"`
	Label      string        `json:"label"`
	Function   functionName  `json:"function"`
	FnEvent    EventListener `json:"event"`
	FnPing     FnPing        `json:"ping"`
	FnRender   FnRender      `json:"render"`
	FnClass    FnClass       `json:"class"`
	FnRedirect FnRedirect    `json:"redirect"`
	FnCustom   FnCustom      `json:"custom"`
	FnError    FnError       `json:"error"`
	// contains filtered or unexported fields
}

Dispatch contains necessary data for the web api.

While this struct is exported, it is not intended to be used directly and is not exposed during runtime.

See: https://kitkitchen.github.io/docs/fncmp/tutorial/context to read about how Dispatch is used.

type DispatchError added in v0.1.0

type DispatchError string
const (
	ErrCtxMissingDispatch DispatchError = "context missing dispatch"
	ErrNoClientConnection DispatchError = "no connection to client"
	ErrConnectionNotFound DispatchError = "connection not found"
	ErrConnectionFailed   DispatchError = "connection failed"
	ErrCtxMissingEvent    DispatchError = "context missing event"
)

func (DispatchError) Error added in v0.1.0

func (e DispatchError) Error() string

type DragEvent added in v0.1.0

type DragEvent struct {
	IsTrusted        bool        `json:"isTrusted"`
	AltKey           bool        `json:"altKey"`
	Bubbles          bool        `json:"bubbles"`
	Button           int         `json:"button"`
	Buttons          int         `json:"buttons"`
	Cancelable       bool        `json:"cancelable"`
	ClientX          int         `json:"clientX"`
	ClientY          int         `json:"clientY"`
	Composed         bool        `json:"composed"`
	CtrlKey          bool        `json:"ctrlKey"`
	CurrentTarget    EventTarget `json:"currentTarget"`
	DefaultPrevented bool        `json:"defaultPrevented"`
	Detail           int         `json:"detail"`
	EventPhase       int         `json:"eventPhase"`
	MetaKey          bool        `json:"metaKey"`
	MovementX        int         `json:"movementX"`
	MovementY        int         `json:"movementY"`
	OffsetX          int         `json:"offsetX"`
	OffsetY          int         `json:"offsetY"`
	PageX            int         `json:"pageX"`
	PageY            int         `json:"pageY"`
	RelatedTarget    EventTarget `json:"relatedTarget"`
}

type EventListener

type EventListener struct {
	context.Context `json:"-"`
	ID              string   `json:"id"`
	TargetID        string   `json:"target_id"`
	Handler         HandleFn `json:"-"`
	On              OnEvent  `json:"on"`
	Data            any      `json:"data"`
}

type EventTarget added in v0.1.0

type EventTarget struct {
	ID         string   `json:"id"`
	ClassList  []string `json:"classList"`
	TagName    string   `json:"tagName"`
	InnerHTML  string   `json:"innerHTML"`
	OuterHTML  string   `json:"outerHTML"`
	Value      string   `json:"value"`
	Checked    bool     `json:"checked"`
	Disabled   bool     `json:"disabled"`
	Hidden     bool     `json:"hidden"`
	Style      string   `json:"style"`
	Attributes []string `json:"attributes"`
	Dataset    []string `json:"dataset"`
}

Event data types

type FnClass added in v0.3.1

type FnClass struct {
	TargetID string   `json:"target_id"`
	Remove   bool     `json:"remove"`
	Names    []string `json:"names"`
}

FnClass is used internally to add or remove classes from elements.

type FnComponent added in v0.1.0

type FnComponent struct {
	context.Context
	// contains filtered or unexported fields
}

FnComponent is a functional component that can be rendered and dispatched to the client

func FnErr added in v0.2.31

func FnErr(ctx context.Context, err error) FnComponent

FnErr returns a FnComponent with an error message

func NewFn added in v0.1.0

func NewFn(ctx context.Context, c Component) FnComponent

NewFn creates a new FnComponent from a Component

func RedirectURL added in v0.1.1

func RedirectURL(ctx context.Context, url string) FnComponent

RedirectURL redirects the client to the given url when returned from a handler

func (FnComponent) AppendElement added in v0.1.1

func (f FnComponent) AppendElement(id string) FnComponent

AppendTarget appends the rendered component to an element by ID in the DOM

func (FnComponent) AppendTag added in v0.1.0

func (f FnComponent) AppendTag(tag string) FnComponent

AppendTag appends the rendered component to a tag in the DOM

func (FnComponent) Dispatch added in v0.1.1

func (f FnComponent) Dispatch()

Dispatch immediately sends the FnComponent to the client

func (FnComponent) JS added in v0.1.0

func (f FnComponent) JS(fn string, arg any) FnComponent

JS sets the FnComponent to run a custom JavaScript function

func (FnComponent) PrependElement added in v0.1.1

func (f FnComponent) PrependElement(id string) FnComponent

PrependTarget prepends the rendered component to an element by ID in the DOM

func (FnComponent) PrependTag added in v0.1.0

func (f FnComponent) PrependTag(tag string) FnComponent

PrependTag prepends the rendered component to a tag in the DOM

func (FnComponent) Render added in v0.1.0

func (f FnComponent) Render(ctx context.Context, w io.Writer) error

Render renders the FnComponent with necessary metadata for the client

func (FnComponent) SwapElementInner added in v0.1.1

func (f FnComponent) SwapElementInner(id string) FnComponent

SwapElementInner swaps the inner HTML of an element by ID in the DOM with the rendered component

func (FnComponent) SwapElementOuter added in v0.1.1

func (f FnComponent) SwapElementOuter(id string) FnComponent

SwapElementOuter swaps the rendered component with an element by ID in the DOM

func (FnComponent) SwapTagInner added in v0.1.0

func (f FnComponent) SwapTagInner(tag string) FnComponent

SwapTagInner swaps the inner HTML of a tag in the DOM with the rendered component

func (FnComponent) SwapTagOuter added in v0.1.0

func (f FnComponent) SwapTagOuter(tag string) FnComponent

SwapTagOuter swaps the rendered component with a tag in the DOM

func (FnComponent) WithContext added in v0.1.0

func (f FnComponent) WithContext(ctx context.Context) FnComponent

WithContext sets the context of the FnComponent

func (FnComponent) WithError added in v0.1.0

func (f FnComponent) WithError(err error) FnComponent

WithError sets the FnComponent to render an error

func (FnComponent) WithEvents added in v0.1.0

func (f FnComponent) WithEvents(h HandleFn, e ...OnEvent) FnComponent

WithEvents sets the event listeners of the FnComponent with variadic OnEvent

func (FnComponent) WithLabel added in v0.1.0

func (f FnComponent) WithLabel(label string) FnComponent

WithLabel sets the label of the component

The label may be used to identify a component on the server and client, especially during debugging.

func (FnComponent) WithRedirect added in v0.1.0

func (f FnComponent) WithRedirect(url string) FnComponent

WithRedirect sets the FnComponent to redirect to a URL

func (FnComponent) Write added in v0.1.0

func (f FnComponent) Write(p []byte) (n int, err error)

Write writes to the FnComponent's buffer

type FnCustom added in v0.1.0

type FnCustom struct {
	Function string `json:"function"`
	Data     any    `json:"data"`
	Result   any    `json:"result"`
}

FnCustom is used internally to run custom JavaScript on the client.

type FnError added in v0.1.0

type FnError struct {
	Message string `json:"message"`
}

FnError is used internally to log an error on the server if config is set to log errors

See: https://pkg.go.dev/github.com/kitkitchen/fncmp#SetConfig

type FnPing added in v0.3.2

type FnPing struct {
	Server bool `json:"server"`
	Client bool `json:"client"`
}

FnPing is used internally to ping the client or server.

type FnRedirect added in v0.1.0

type FnRedirect struct {
	URL string `json:"url"`
}

FnRedirect is used internally to redirect the client to a new URL.

type FnRender added in v0.1.0

type FnRender struct {
	TargetID       string          `json:"target_id"`
	Tag            string          `json:"tag"`
	Inner          bool            `json:"inner"`
	Outer          bool            `json:"outer"`
	Append         bool            `json:"append"`
	Prepend        bool            `json:"prepend"`
	Remove         bool            `json:"remove"`
	HTML           string          `json:"html"`
	EventListeners []EventListener `json:"event_listeners"`
}

FnRender is used internally to render HTML to the client.

type FormDataEvent added in v0.1.0

type FormDataEvent struct {
	IsTrusted        bool           `json:"isTrusted"`
	Bubbles          bool           `json:"bubbles"`
	Cancelable       bool           `json:"cancelable"`
	Composed         bool           `json:"composed"`
	CurrentTarget    EventTarget    `json:"currentTarget"`
	DefaultPrevented bool           `json:"defaultPrevented"`
	EventPhase       int            `json:"eventPhase"`
	FormData         map[string]any `json:"formData"`
}

type HTML added in v0.1.0

type HTML string

HTML implements the Component interface for a string of HTML

func (HTML) Render added in v0.1.0

func (h HTML) Render(ctx context.Context, w io.Writer) error

func (*HTML) Write added in v0.2.31

func (h *HTML) Write(p []byte) (n int, err error)

type HandleFn added in v0.1.0

type HandleFn func(context.Context) FnComponent

type KeyboardEvent added in v0.1.0

type KeyboardEvent struct {
	IsTrusted        bool        `json:"isTrusted"`
	AltKey           bool        `json:"altKey"`
	Bubbles          bool        `json:"bubbles"`
	Cancelable       bool        `json:"cancelable"`
	Code             string      `json:"code"`
	Composed         bool        `json:"composed"`
	CtrlKey          bool        `json:"ctrlKey"`
	CurrentTarget    EventTarget `json:"currentTarget"`
	DefaultPrevented bool        `json:"defaultPrevented"`
	Detail           int         `json:"detail"`
	EventPhase       int         `json:"eventPhase"`
	IsComposing      bool        `json:"isComposing"`
	Key              string      `json:"key"`
	Location         int         `json:"location"`
	MetaKey          bool        `json:"metaKey"`
	Repeat           bool        `json:"repeat"`
	ShiftKey         bool        `json:"shiftKey"`
}

type LogLevel added in v0.1.1

type LogLevel log.Level
const (
	Debug LogLevel = -4
	Info  LogLevel = 0
	Warn  LogLevel = 4
	Error LogLevel = 8
	Fatal LogLevel = 12
	None  LogLevel = math.MaxInt32
)

type MouseEvent added in v0.1.0

type MouseEvent struct {
	IsTrusted        bool        `json:"isTrusted"`
	AltKey           bool        `json:"altKey"`
	Bubbles          bool        `json:"bubbles"`
	Button           int         `json:"button"`
	Buttons          int         `json:"buttons"`
	Cancelable       bool        `json:"cancelable"`
	ClientX          int         `json:"clientX"`
	ClientY          int         `json:"clientY"`
	Composed         bool        `json:"composed"`
	CtrlKey          bool        `json:"ctrlKey"`
	CurrentTarget    EventTarget `json:"currentTarget"`
	DefaultPrevented bool        `json:"defaultPrevented"`
	Detail           int         `json:"detail"`
	EventPhase       int         `json:"eventPhase"`
	MetaKey          bool        `json:"metaKey"`
	MovementX        int         `json:"movementX"`
	MovementY        int         `json:"movementY"`
	OffsetX          int         `json:"offsetX"`
	OffsetY          int         `json:"offsetY"`
	PageX            int         `json:"pageX"`
	PageY            int         `json:"pageY"`
	RelatedTarget    EventTarget `json:"relatedTarget"`
}

type OnEvent

type OnEvent string
const (
	OnAbort              OnEvent = "abort"
	OnAnimationEnd       OnEvent = "animationend"
	OnAnimationIteration OnEvent = "animationiteration"
	OnAnimationStart     OnEvent = "animationstart"
	OnBlur               OnEvent = "blur"
	OnCanPlay            OnEvent = "canplay"
	OnCanPlayThrough     OnEvent = "canplaythrough"
	OnChange             OnEvent = "change"
	OnChangeCapture      OnEvent = "changecapture"
	OnClick              OnEvent = "click"
	OnCompositionEnd     OnEvent = "compositionend"
	OnCompositionStart   OnEvent = "compositionstart"
	OnCompositionUpdate  OnEvent = "compositionupdate"
	OnContextMenuCapture OnEvent = "contextmenucapture"
	OnCopy               OnEvent = "copy"
	OnCut                OnEvent = "cut"
	OnDoubleClickCapture OnEvent = "doubleclickcapture"
	OnDrag               OnEvent = "drag"
	OnDragEnd            OnEvent = "dragend"
	OnDragEnter          OnEvent = "dragenter"
	OnDragExitCapture    OnEvent = "dragexitcapture"
	OnDragLeave          OnEvent = "dragleave"
	OnDragOver           OnEvent = "dragover"
	OnDragStart          OnEvent = "dragstart"
	OnDrop               OnEvent = "drop"
	OnDurationChange     OnEvent = "durationchange"
	OnEmptied            OnEvent = "emptied"
	OnEncrypted          OnEvent = "encrypted"
	OnEnded              OnEvent = "ended"
	OnError              OnEvent = "error"
	OnFocus              OnEvent = "focus"
	OnGotPointerCapture  OnEvent = "gotpointercapture"
	OnInput              OnEvent = "input"
	OnInvalid            OnEvent = "invalid"
	OnKeyDown            OnEvent = "keydown"
	OnKeyPress           OnEvent = "keypress"
	OnKeyUp              OnEvent = "keyup"
	OnLoad               OnEvent = "load"
	OnLoadEnd            OnEvent = "loadend"
	OnLoadStart          OnEvent = "loadstart"
	OnLoadedData         OnEvent = "loadeddata"
	OnLoadedMetadata     OnEvent = "loadedmetadata"
	OnLostPointerCapture OnEvent = "lostpointercapture"
	OnMouseDown          OnEvent = "mousedown"
	OnMouseEnter         OnEvent = "mouseenter"
	OnMouseLeave         OnEvent = "mouseleave"
	OnMouseMove          OnEvent = "mousemove"
	OnMouseOut           OnEvent = "mouseout"
	OnMouseOver          OnEvent = "mouseover"
	OnMouseUp            OnEvent = "mouseup"
	OnPause              OnEvent = "pause"
	OnPlay               OnEvent = "play"
	OnPlaying            OnEvent = "playing"
	OnPointerCancel      OnEvent = "pointercancel"
	OnPointerDown        OnEvent = "pointerdown"
	OnPointerEnter       OnEvent = "pointerenter"
	OnPointerLeave       OnEvent = "pointerleave"
	OnPointerMove        OnEvent = "pointermove"
	OnPointerOut         OnEvent = "pointerout"
	OnPointerOver        OnEvent = "pointerover"
	OnPointerUp          OnEvent = "pointerup"
	OnProgress           OnEvent = "progress"
	OnRateChange         OnEvent = "ratechange"
	OnResetCapture       OnEvent = "resetcapture"
	OnScroll             OnEvent = "scroll"
	OnSeeked             OnEvent = "seeked"
	OnSeeking            OnEvent = "seeking"
	OnSelectCapture      OnEvent = "selectcapture"
	OnStalled            OnEvent = "stalled"
	OnSubmit             OnEvent = "submit"
	OnSuspend            OnEvent = "suspend"
	OnTimeUpdate         OnEvent = "timeupdate"
	OnToggle             OnEvent = "toggle"
	OnTouchCancel        OnEvent = "touchcancel"
	OnTouchEnd           OnEvent = "touchend"
	OnTouchMove          OnEvent = "touchmove"
	OnTouchStart         OnEvent = "touchstart"
	OnTransitionEnd      OnEvent = "transitionend"
	OnVolumeChange       OnEvent = "volumechange"
	OnWaiting            OnEvent = "waiting"
	OnWheel              OnEvent = "wheel"
)

DOM event types

type PointerEvent added in v0.1.0

type PointerEvent struct {
	IsTrusted        bool        `json:"isTrusted"`
	AltKey           bool        `json:"altKey"`
	Bubbles          bool        `json:"bubbles"`
	Button           int         `json:"button"`
	Buttons          int         `json:"buttons"`
	Cancelable       bool        `json:"cancelable"`
	ClientX          int         `json:"clientX"`
	ClientY          int         `json:"clientY"`
	Composed         bool        `json:"composed"`
	CtrlKey          bool        `json:"ctrlKey"`
	CurrentTarget    EventTarget `json:"currentTarget"`
	DefaultPrevented bool        `json:"defaultPrevented"`
	Detail           int         `json:"detail"`
	EventPhase       int         `json:"eventPhase"`
	Height           int         `json:"height"`
	IsPrimary        bool        `json:"isPrimary"`
	MetaKey          bool        `json:"metaKey"`
	MovementX        int         `json:"movementX"`
	MovementY        int         `json:"movementY"`
	OffsetX          int         `json:"offsetX"`
	OffsetY          int         `json:"offsetY"`
	PageX            int         `json:"pageX"`
	PageY            int         `json:"pageY"`
	PointerId        int         `json:"pointerId"`
	PointerType      string      `json:"pointerType"`
	Pressure         int         `json:"pressure"`
	RelatedTarget    EventTarget `json:"relatedTarget"`
}

type Touch added in v0.1.0

type Touch struct {
	ClientX       int         `json:"clientX"`
	ClientY       int         `json:"clientY"`
	Identifier    int         `json:"identifier"`
	PageX         int         `json:"pageX"`
	PageY         int         `json:"pageY"`
	RadiusX       float64     `json:"radiusX"`
	RadiusY       float64     `json:"radiusY"`
	RotationAngle int         `json:"rotationAngle"`
	ScreenX       int         `json:"screenX"`
	ScreenY       int         `json:"screenY"`
	Target        EventTarget `json:"target"`
}

type TouchEvent added in v0.1.0

type TouchEvent struct {
	ChangedTouches []Touch `json:"changedTouches"`
	TargetTouches  []Touch `json:"targetTouches"`
	Touches        []Touch `json:"touches"`
	LayerX         int     `json:"layerX"`
	LayerY         int     `json:"layerY"`
	PageX          int     `json:"pageX"`
	PageY          int     `json:"pageY"`
}

type Writer added in v0.1.0

type Writer struct {
	http.ResponseWriter
	// contains filtered or unexported fields
}

func (*Writer) Write added in v0.1.0

func (w *Writer) Write(p []byte) (n int, err error)

Jump to

Keyboard shortcuts

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