fncmp

package module
v0.3.305 Latest Latest
Warning

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

Go to latest
Published: Oct 17, 2024 License: MIT Imports: 15 Imported by: 0

Documentation

Overview

Package fncmp brings enhanced functionality to the Component interface.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AddClasses

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

AddClasses adds classes to an element by ID in the DOM

func EventData

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

EventData unmarshals event listener data T from the client

func JS

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

JS runs a custom JavaScript function on the client

func MiddleWareFn

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

func OnCacheChange

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

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

func OnCacheTimeOut

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

OnCacheTimeOut sets a function to be called when the cache expires

func RemoveClasses

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

RemoveClasses removes classes from an element by ID in the DOM

func RemoveElement

func RemoveElement(ctx context.Context, id string)

Remove element by ID in the DOM

func RemoveTag

func RemoveTag(ctx context.Context, tag string)

Remove tag in the DOM

func RenderComponent

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

RenderComponent renders a component and returns the HTML string

func SetConfig

func SetConfig(c *Config)

Types

type Cache

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

func NewCache

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

func UseCache

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

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

CreatedAt returns the time the cache was created

func (*Cache[T]) Delete

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

Delete removes the cache from the store

func (*Cache[T]) Expiry

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

Expiry returns expiry time of the cache

func (*Cache[T]) History

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

GetHistory returns the history of the cache

func (*Cache[T]) Record

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

History returns the history of the cache

func (*Cache[T]) Set

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

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

func (*Cache[T]) UpdatedAt

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

UpdatedAt returns the time the cache was last updated

func (*Cache[T]) Value

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

Value returns the current value of the cache

type CacheError

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

func (e CacheError) Error() string

type CacheOnFn

type CacheOnFn string

type Component

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

type Config

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

func (c *Config) Set()

type ContextKey

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

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

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

func (e DispatchError) Error() string

type DragEvent

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

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

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

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

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

FnErr returns a FnComponent with an error message

func NewFn

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

NewFn creates a new FnComponent from a Component

func RedirectURL

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

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

func (FnComponent) AppendElement

func (f FnComponent) AppendElement(id string) FnComponent

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

func (FnComponent) AppendTag

func (f FnComponent) AppendTag(tag string) FnComponent

AppendTag appends the rendered component to a tag in the DOM

func (FnComponent) Dispatch

func (f FnComponent) Dispatch()

Dispatch immediately sends the FnComponent to the client

func (FnComponent) JS

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

JS sets the FnComponent to run a custom JavaScript function

func (FnComponent) PrependElement

func (f FnComponent) PrependElement(id string) FnComponent

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

func (FnComponent) PrependTag

func (f FnComponent) PrependTag(tag string) FnComponent

PrependTag prepends the rendered component to a tag in the DOM

func (FnComponent) Render

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

Render renders the FnComponent with necessary metadata for the client

func (FnComponent) SwapElementInner

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

func (f FnComponent) SwapElementOuter(id string) FnComponent

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

func (FnComponent) SwapTagInner

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

func (f FnComponent) SwapTagOuter(tag string) FnComponent

SwapTagOuter swaps the rendered component with a tag in the DOM

func (FnComponent) WithContext

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

WithContext sets the context of the FnComponent

func (FnComponent) WithError

func (f FnComponent) WithError(err error) FnComponent

WithError sets the FnComponent to render an error

func (FnComponent) WithEvents

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

WithEvents sets the event listeners of the FnComponent with variadic OnEvent

func (FnComponent) WithLabel

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

func (f FnComponent) WithRedirect(url string) FnComponent

WithRedirect sets the FnComponent to redirect to a URL

func (FnComponent) Write

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

Write writes to the FnComponent's buffer

type FnCustom

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

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

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

FnPing is used internally to ping the client or server.

type FnRedirect

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

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

type FnRender

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

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

type HTML string

HTML implements the Component interface for a string of HTML

func (HTML) Render

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

func (*HTML) Write

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

type HandleFn

type HandleFn func(context.Context) FnComponent

type KeyboardEvent

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

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

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

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

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

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

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

func (*Writer) Write

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