live

package
v0.0.0-...-52ea55a Latest Latest
Warning

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

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

Documentation

Index

Constants

View Source
const DefaultTransitionDuration = 200 * time.Millisecond

DefaultTransitionDuration_ms is the default duration, in milliseconds, of live.JS transitions.

Variables

This section is empty.

Functions

func AllowUpload

func AllowUpload(ctx context.Context, name string, options UploadConstraints) error

Allows file uploads for the given `LiveView`and configures the upload options (filetypes, size, etc).

func CancelUpload

func CancelUpload(ctx context.Context, configName string, ref string) error

Cancels the file upload for a given UploadConfig by config name and file ref.

func ConsumeUploadedEntries

func ConsumeUploadedEntries[T any](
	ctx context.Context,
	configName string,
	fn func(meta ConsumeUploadedEntriesMeta, entry UploadEntry) T,
) []T

Consume the uploaded files for a given UploadConfig (by name). This should only be called after the form's "save" event has occurred which guarantees all the files for the upload have been fully uploaded.

func FileInputTag

func FileInputTag(uc UploadConfig, cssClasses string) (htmltmpl.HTML, error)

FileInputTag renders a file input tag for uploading files to a View.

func Funcs

func Funcs() htmltmpl.FuncMap

Funcs provides some useful function for live.View templates:

  • liveTitleTag: renders a title tag that can be updated from Views
  • liveNav: renders "live" navigation links that support navigating without a page refresh
  • liveViewTag: renders a container for a live.View - required for layoutTemplates
  • liveFileInput: renders a file input tag for uploading files to a View
  • liveImgPreview: renders an image preview for file to be uploaded to a View
  • submitTag: renders a submit fuction that supports the PhxDisableWith feature

func GetView

func GetView[T View](r *http.Request) T

GetView returns the View of type T corresponding to r. If no such view has been set, returns the zero value for T.

func ImagePreviewTag

func ImagePreviewTag(e UploadEntry) (htmltmpl.HTML, error)

ImagePreviewTag renders a preview image for a file upload.

func LiveViewTag

func LiveViewTag(ld *LayoutDot) (htmltmpl.HTML, error)

LiveView renders a container for a live.View - required for layoutTemplates.

func MakeView

func MakeView[T View](r *http.Request) T

MakeView will either get the existing View of type T associated with r or create a View of type T. If r is not a LiveView-enabled request, returns the zero value of T.

func Navigation(linkType, path string, params map[string]any, text string) (htmltmpl.HTML, error)

Navigation renders "live" navigation links that support navigating without a page refresh.

func PageTitle

func PageTitle(ctx context.Context, newTitle string)

PageTitle updates the page title for the View

func PushEvent

func PushEvent(ctx context.Context, e Event) error

PushEvent sends an event to the View which a Hook can respond to

func PushNav

func PushNav(ctx context.Context, typ LiveNavType, path string, params url.Values, replaceHistory bool) error

PushNav supports push patching and push redirecting from server to View

func Redirect

func Redirect(ctx context.Context, url *url.URL) error

Redirect sends an event to the View that triggers a full page load to url.

func SendInfo

func SendInfo(ctx context.Context, info *Info)

SendInfo sends an internal event to the View if it is connected to a WebSocket

func SetView

func SetView(r *http.Request, v View)

SetView marks r as corresponding to v. Its handler will result in a rendered LiveView.

func SubmitTag

func SubmitTag(label string, opts ...map[string]any) (htmltmpl.HTML, error)

SubmitTag renders a submit button with support for the PhxDisableWith option.

func TitleTag

func TitleTag(config PageTitleConfig) (htmltmpl.HTML, error)

TitleTag renders a title tag that can be updated from Views.

func UploadedEntries

func UploadedEntries(ctx context.Context, configName string) (completed []UploadEntry, inProgress []UploadEntry)

Returns two sets of files that are being uploaded, those `completed` and those `inProgress` for a given UploadConfig (by name). Unlike `consumeUploadedEntries`, this does not require the form's "save" event to have occurred and will not throw if any of the entries are not fully uploaded.

Types

type Config

type Config struct {
	// Mux is a http.Handler that routes requests to Views.
	Mux http.Handler
	// ShouldHandleRequest indicates whether this Config should handle r.
	// If nil, it is assumed to return true.
	// This can be helpful when live views co-exist with non-live views.
	ShouldHandleRequest func(r *http.Request) bool
	// RenderLayout is a func that provides a way to render your base layout HTML for all LiveViews.
	// You are provides with the http.ResponseWriter, *http.Request, and a *LayoutDot and are responsible for
	// providing the "dot" and the template that will be executed on the initial HTML render.
	// Your template should always do at least the following:
	//  - Load your LiveView Client Javascript (e.g. <script defer type="text/javascript" src="/js/index.js"></script>) without this, your LiveView will not work.
	//  - Pass the LayoutDot to the liveViewContainerTag (i.e. {{ liveViewContainerTag .LayoutDot }})
	//  - Set the CSRF token in a meta tag (i.e. <meta name="csrf-token" content="{{ .LayoutDot.CSRFToken }}">)
	RenderLayout func(http.ResponseWriter, *http.Request, *LayoutDot) (any, *htmltmpl.Template)
	// OnViewError is called when an error occurs during a View lifecycle method (e.g. HandleEvent, HandleInfo, etc)
	// AND the view is connected to a socket (as opposed to the initial HTTP request). OnViewError may be nil
	// in which case the error is not logged or handled in any way.  Regardless of whether OnViewError is non-nil,
	// the javascript client will receive a "phx_error" message via the connected socket which in the case
	// of `HandleEvent` and `HandleInfo` will result in the client attempting to re-join the View.  For `HandleParams`,
	// the error will result in a page reload which will start the HTTP request lifecycle over again.
	OnViewError func(ctx context.Context, v View, url *url.URL, err error)
}

Config is the configuration for a live application.

func (*Config) Middleware

func (c *Config) Middleware(next http.Handler) http.Handler

type ConsumeUploadedEntriesMeta

type ConsumeUploadedEntriesMeta struct {
	//  The location of the file on the server
	Path string
}

type Event

type Event struct {
	Type string
	Data url.Values
}

Event is the event data sent from the client

func (*Event) MarshalJSON

func (e *Event) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler for Event

type EventHandler

type EventHandler interface {
	HandleEvent(context.Context, *Event) error
}

EventHandler is an interface that can be implemented by a View to be notified when user events are received from the client.

type HTTPHandler

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

HTTPHandler handles HTTP requests for a View

func NewHTTPHandler

func NewHTTPHandler(c Config) *HTTPHandler

NewHTTPHandler returns a new HTTPHandler with the given config

type HideOpts

type HideOpts struct {
	// To is the DOM selector of the element to hide, or empty to target the interacted element.
	To string
	// Transition to apply, if any.
	Transition *Transition
	// Time is the duration of the transition, if present; defaults to DefaultTransitionDuration if 0.
	Time time.Duration
}

func (*HideOpts) MarshalJSON

func (o *HideOpts) MarshalJSON() ([]byte, error)

type Info

type Info Event

Info is internal event data from the server

type InfoHandler

type InfoHandler interface {
	HandleInfo(context.Context, *Info) error
}

InfoHandler is an interface that can be implemented by a View to be notified when info (i.e. "internal") messages are received from the server.

type JS

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

JS provides a way to precompose simple client-side DOM changes that don't require a round-trip to the server. Create a JS struct, call its methods to build up a command, and then render it as the value of a phx-* attribute.

func (*JS) Hide

func (js *JS) Hide(opts *HideOpts) *JS

Hide hides elements. When the action is triggered on the client, phx:hide-start is dispatched to the hidden elements. After the time specified by :time, phx:hide-end is dispatched.

func (*JS) MarshalJSON

func (js *JS) MarshalJSON() ([]byte, error)

func (*JS) Push

func (js *JS) Push(event string, opts *PushOpts) *JS

Push pushes an event to the server.

func (*JS) Show

func (js *JS) Show(opts *ShowOpts) *JS

Show shows elements. When the action is triggered on the client, phx:show-start is dispatched to the shown elements. After the time specified by :time, phx:show-end is dispatched.

func (*JS) String

func (js *JS) String() string

func (*JS) Toggle

func (js *JS) Toggle(opts *ToggleOpts) *JS

Toggle toggles element visibility. When the toggle is complete on the client, a phx:show-start or phx:hide-start, and phx:show-end or phx:hide-end event will be dispatched to the toggled elements.

type LayoutDot

type LayoutDot struct {
	PageTitle  PageTitleConfig
	Static     string
	LiveViewID string
	CSRFToken  string
	// contains filtered or unexported fields
}

LayoutDot is the information available when initially writing our your container layout. It should be passed into the liveViewContainerTag funcmap func if you choose to use it.

func (*LayoutDot) ExecuteViewTemplate

func (d *LayoutDot) ExecuteViewTemplate(buf *strings.Builder) error

type LiveNavType

type LiveNavType string
const (
	NavPatch    LiveNavType = "live_patch"
	NavRedirect LiveNavType = "live_redirect"
)

type Meta

type Meta struct {
	CSRFToken string
	URL       url.URL
	Uploads   map[string]*UploadConfig
}

Meta is the metadata passed to a View's Render method as well as added to the template context via the .Meta field.

type Mounter

type Mounter interface {
	Mount(context.Context, Params) error
}

Mounter is an interface that can be implemented by a View to be notified when it is mounted.

type PageTitleConfig

type PageTitleConfig struct {
	Title  string
	Prefix string
	Suffix string
}

PageTitleConfig structures the contents of a page’s title tag. It’s available in WriteLayout for your own use, and subsequent PageTitle() calls will update the title while preserving Prefix and Suffix.

type PageTitleConfigurer

type PageTitleConfigurer interface {
	PageTitleConfig() PageTitleConfig
}

PageTitleConfgurer is an interface that can be implemented by a View to configure the liveTitleTag template function.

type Params

type Params struct {
	CSRFToken string
	Mounts    int
	Data      map[string]any
}

Params is the data passed to a View's Mount method.

type ParamsHandler

type ParamsHandler interface {
	HandleParams(context.Context, *url.URL) error
}

ParamsHandler is an interface that can be implemented by a View to be notified when the URL parameters change (and after a view is first mounted).

type PushOpts

type PushOpts struct {
	// Target is the selector or component ID to push to
	Target string `json:"target,omitempty"`
	// Loading is the selector to apply the phx loading classes to
	Loading string `json:"loading,omitempty"`
	// PageLoading is a boolean indicating whether to trigger the "phx:page-loading-start"
	// and "phx:page-loading-stop" events. Defaults to `false`
	PageLoading bool `json:"page_loading,omitempty"`
	// Value is optional data to include in the event's `value` property
	Value any `json:"value,omitempty"`
}

type Router

type Router = func(*url.URL) View

A Router creates a Handler given a URL. TODO: rethink this with a better muxer, maybe the standard library muxer.

type ShowOpts

type ShowOpts struct {
	// To is the DOM selector of the element to show, or empty to target the interacted element.
	To string
	// Transition to apply, if any.
	Transition *Transition
	// Time is the duration of the transition, if present; defaults to DefaultTransitionDuration if 0.
	Time time.Duration
	// Display is the CSS display value to set when showing; defaults to "block".
	Display string
}

func (*ShowOpts) MarshalJSON

func (o *ShowOpts) MarshalJSON() ([]byte, error)

type ToggleOpts

type ToggleOpts struct {
	// To is the DOM selector of the element to toggle visibility of, or empty to target the interacted element.
	To string
	// In is the transition to apply when showing the element.
	In *Transition
	// Out is the transition to apply when hiding the element.
	Out *Transition
	// Time is the duration of the transition, if present; defaults to DefaultTransitionDuration if 0.
	Time time.Duration
	// Display is the CSS display value to set when showing; defaults to "block".
	Display string
}

func (*ToggleOpts) MarshalJSON

func (o *ToggleOpts) MarshalJSON() ([]byte, error)

type Transition

type Transition struct {
	// TransitionClass is the CSS transition class(es) to apply for the duration of the transition.
	TransitionClass string
	// StartClass is the CSS class(es) that apply at the start of a transition.
	StartClass string
	// EndClass is the CSS class(es) that apply at the end of a transition.
	EndClass string
}

Transition describes a set of CSS class changes over time.

func (Transition) MarshalJSON

func (t Transition) MarshalJSON() ([]byte, error)

type UploadConfig

type UploadConfig struct {
	// Name is the unique of the upload config referenced in the LiveView
	Name string

	// Entries are the set of UploadEntries selected for upload
	Entries []UploadEntry

	// Ref is the unique instance ref of the upload config
	Ref string

	// Errors contains the set of errors that have occurred during selection or upload.
	Errors []string

	// AutoUpload determines whether to upload the selected files automatically when selected on the client. Defaults to false.
	AutoUpload bool

	UploadConstraints
}

UploadConfig is the configuration and entry related details for uploading files.

func (*UploadConfig) AddEntries

func (uc *UploadConfig) AddEntries(entries []any)

AddEnties adds all the entries to the upload config and validates each entry and the config as a whole

func (*UploadConfig) RemoveEntry

func (uc *UploadConfig) RemoveEntry(ref string)

RemoveEntry removes an entry from the upload config for given ref

type UploadConstraints

type UploadConstraints struct {
	// Accept is the slice of unique file type specifiers that can be uploaded.
	// See https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/file#unique_file_type_specifiers
	Accept []string

	// MaxEntries is the maximum number of files that can be uploaded at once. Defaults to 10.
	MaxEntries int `json:"max_entries"`

	// MaxFileSize is maximum size of each file in bytes. Defaults to 10MB.
	MaxFileSize int64 `json:"max_file_size"`

	// ChunkSize is the size of each chunk of an uploaded file in bytes. Defaults to 64kb.
	ChunkSize int64 `json:"chunk_size"`
}

UploadConstraints contains the file constraints for the upload config

func NewUploadConstraints

func NewUploadConstraints(uc *UploadConfig) UploadConstraints

NewUploadConstraints returns a new UploadConstraints merged with the default values

type UploadEntry

type UploadEntry struct {
	// Whether the file selection has been cancelled. Defaults to false.
	Cancelled bool

	// The timestamp when the file was last modified from the client's file system
	LastModified int64

	// The name of the file from the client's file system
	Name string

	// The size of the file in bytes from the client's file system
	Size int64

	// The mime type of the file from the client's file system
	Type string

	// True if the file has been uploaded. Defaults to false.
	Done bool

	// True if the file has been auto-uploaded. Defaults to false.
	Preflighted bool

	// The integer percentage of the file that has been uploaded. Defaults to 0.
	Progress int

	// The unique instance ref of the upload entry
	Ref string

	// The unique instance ref of the upload config to which this entry belongs
	UploadRef string

	// A uuid for the file
	UUID string // uuid.UUID

	// True if there are no errors with the file. Defaults to true.
	Valid bool

	// Errors that have occurred during selection or upload.
	Errors []string
}

A file and related metadata selected for upload

type View

type View interface {
	// Render returns the dot and template needed to turn a LiveView into HTML.
	// Commonly the returned dot is the receiver; however, any data needed to render the template is acceptable.
	// Note that if the View uses any upload live.Funcs() the *Meta argument should be passed through to the template.
	Render(context.Context, *Meta) (any, *htmltmpl.Template)
}

View is a live view which requires a Render method in order to be rendered for HTML and WebSocket requests.

type WebsocketHandler

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

WebsocketHandler handles Websocket requests and message routing.

func NewWebsocketHandler

func NewWebsocketHandler(c Config) *WebsocketHandler

NewWebsocketHandler returns a http.Handler that handles upgrading HTTP requests to WebSockets and handling message routing.

func (*WebsocketHandler) ServeHTTP

func (x *WebsocketHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)

Directories

Path Synopsis
internal
phx

Jump to

Keyboard shortcuts

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