gr

package module
v0.0.0-...-52c9d7f Latest Latest
Warning

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

Go to latest
Published: Aug 17, 2017 License: Apache-2.0 Imports: 8 Imported by: 37

README

Go React

Build Status GoDoc Go Report Card

See Also:

GopherJS bindings for Facebook React.

NOTE: Still early and not production ready.

Examples

NOTE: Make sure that your GopherJS is up-to-date before running these: go get -u github.com/gopherjs/gopherjs

For a live demo of the examples below, see http://bego.io/gr/ (may not be up-to-date).

There are some runnable examples in /examples. Just navigate to that folder and do a:

gopherjs serve

Then navigate to http://localhost:8080/github.com/bep/gr/examples/.

To get a sense of the API, here is the click-counter example:

func main() {
	component := gr.New(new(clickCounter))

	gr.RenderLoop(func() {
		component.Render("react", gr.Props{})
	})
}

type clickCounter struct {
	*gr.This
}

// Implements the StateInitializer interface.
func (c clickCounter) GetInitialState() gr.State {
	return gr.State{"counter": 0}
}

// Implements the Renderer interface.
func (c clickCounter) Render() gr.Component {
	counter := c.State()["counter"]
	message := fmt.Sprintf(" Click me! Number of clicks: %v", counter)

	elem := el.Div(
		el.Button(
			gr.CSS("btn", "btn-lg", "btn-primary"),
			gr.Style("color", "orange"),
			gr.Text(message),
			evt.Click(c.onClick)))

	return examples.Example("Click Counter", elem)
}

func (c clickCounter) onClick(event *gr.Event) {
	c.SetState(gr.State{"counter": c.State().Int("counter") + 1})
}

// Implements the ShouldComponentUpdate interface.
func (c clickCounter) ShouldComponentUpdate(next gr.Cops) bool {
	return c.State().HasChanged(next.State, "counter")
}

For help installing GopherJS, please visit that cool project.

Inspiration

This project is highly inspired by Vecty, a promising and pure Go React-like framework. If you're not heavily invested in Facebook's React, take that for a spin.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var Discard = new(discard)

Discard is a Modifier that does nothing.

View Source
var Dynamic = new(dynamicModifier)

Dynamic is a Modifier that marks the element as dynamic, i.e. not static. This will turn off static features such as adding missing keys.

Functions

func RenderLoop

func RenderLoop(render func(), interval ...time.Duration) chan struct{}

RenderLoop runs the given render func in a loop at the given interval. It can be stopped by closing the returned channel.

func UnmountComponentAtNode

func UnmountComponentAtNode(elementID string) bool

UnmountComponentAtNode unmounts the DOM element at the given ID.

Types

type ChildContextProvider

type ChildContextProvider interface {
	GetChildContext() Context
}

ChildContextProvider provides the context for the children.

The GetChildContext function will be called when the state or props changes. In order to update data in the context, trigger a local state update with this.SetState. This will trigger a new context and changes will be received by the children.

GetChildContext will also be called once in the init phase, to determine the types for the context properties. The this will be nil in this single invocation, and there is no need to return real data as long as the types are real (in cases where this is an expensive operation).

See https://facebook.github.io/react/docs/context.html

type Children

type Children struct {
	*js.Object
}

Children represents a component's child component(s). This is a fairly complex topic in Facebook's React, and more support may arrive here, eventually. See https://facebook.github.io/react/tips/children-props-type.html

func (*Children) Element

func (c *Children) Element() *Element

Element returns the children as an Element ready to render.

type Component

type Component interface {
	Node() *js.Object
}

A Component represents a React JS component.

http://facebook.github.io/react/docs/glossary.html#react-nodes for a reference.

A Component can be either a constructed element (analogous to a ReactElement) or a factory (a ReactClass or a ReactFactory). Factories are identified by their implementation of the Factory interface.

type ComponentConfig

type ComponentConfig struct {
	ContextTypesTemplate Context
}

ComponentConfig is used to add optional static configuration to a component.

type ComponentDidMount

type ComponentDidMount interface {
	ComponentDidMount()
}

ComponentDidMount gets invoked once, only on the client (not on the server), immediately after the initial rendering occurs.

type ComponentDidUpdate

type ComponentDidUpdate interface {
	ComponentDidUpdate(prev Cops)
}

ComponentDidUpdate gets invoked immediately after the component's updates are flushed to the DOM. This method is not called for the initial render.

type ComponentWillMount

type ComponentWillMount interface {
	ComponentWillMount()
}

ComponentWillMount get invoked once, both on the client and server, immediately before the initial rendering occurs.

type ComponentWillReceiveProps

type ComponentWillReceiveProps interface {
	ComponentWillReceiveProps(next Cops)
}

ComponentWillReceiveProps gets invoked when a component is receiving new props. This method is not called for the initial render.

type ComponentWillUnmount

type ComponentWillUnmount interface {
	ComponentWillUnmount()
}

ComponentWillUnmount gets invoked immediately before a component is unmounted from the DOM.

type ComponentWillUpdate

type ComponentWillUpdate interface {
	ComponentWillUpdate(next Cops)
}

ComponentWillUpdate gets invoked immediately before rendering when new props or state are being received. This is not called for the initial render.

type Context

type Context map[string]interface{}

Context holds the React context.

type Cops

type Cops struct {
	Context Context
	Props   Props
	State   State
}

Cops holds COntext, Props and State received in the lifecycle methods. Note that any of these can be nil, depending on the context.

type Element

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

Element represents a builder for a ReactElement. An Element can be a simple text node or a HTML element with children, attributes etc.

func CreateIfNeeded

func CreateIfNeeded(c Component) *Element

CreateIfNeeded evaluates the given Component and returns an Element, creating a new instance if needed. This is a convenience method; if you need to pass properties, use the factory directly.

func NewElement

func NewElement(tag string) *Element

NewElement creates a new Element with the given tag.

func NewPreparedElement

func NewPreparedElement(o *js.Object) *Element

NewPreparedElement creates an Element from a ready-to-use React element.

func (*Element) Modify

func (e *Element) Modify(in *Element)

Modify implements the Modifier interface.

func (*Element) Node

func (e *Element) Node() *js.Object

Node returns the resulting ReactElement.

type Event

type Event struct {
	*js.Object
	This *This
}

Event represents a browser event. See https://developer.mozilla.org/en-US/docs/Web/Events

func (*Event) CurrentTarget

func (e *Event) CurrentTarget() *js.Object

CurrentTarget gives the currentTarget, i.e. the container triggering this event.

func (*Event) Int

func (e *Event) Int(key string) int

Int is a convenience method to get an Event attribute as an Int value, e.g. screenX.

func (*Event) Persist

func (e *Event) Persist()

Persist can be used to make sure the event survives Facebook React's recycling of events. Useful to avoid confusing debugging sessions in the console.

func (*Event) Target

func (e *Event) Target() *js.Object

Target gives the target triggering this event.

func (*Event) TargetValue

func (e *Event) TargetValue() *js.Object

TargetValue gives the target triggering this event's value. For a input select, this will be the selected value.

type EventListener

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

An EventListener can be attached to a HTML element to listen for events, mouse clicks etc.

func NewEventListener

func NewEventListener(name string, listener func(*Event)) *EventListener

NewEventListener creates a new EventListener. In most cases you will use the predefined event listeners in the evt package.

func (*EventListener) Modify

func (l *EventListener) Modify(element *Element)

Modify implements the Modifier interface.

func (*EventListener) PreventDefault

func (l *EventListener) PreventDefault() *EventListener

PreventDefault prevents the default event behaviour in the browser.

func (*EventListener) StopPropagation

func (l *EventListener) StopPropagation() *EventListener

StopPropagation prevents further propagation of the current event in the capturing and bubbling phases.

See https://developer.mozilla.org/en-US/docs/Web/API/Event/stopPropagation.

type Factory

type Factory interface {
	Component
	CreateElement(props Props, children ...Component) *Element
}

A Factory is a Component that can construct Elements (analogous to a ReactClass or a ReactFactory).

type HostInfo

type HostInfo struct {
	Path     string
	Port     int
	Host     string
	Href     string
	Protocol string
	Origin   string
}

HostInfo represents the location info from the browser window. TODO(bep) get rid of all below.

func Location

func Location() HostInfo

Location returns info about the current browser location.

type Lifecycler

Lifecycler contains all the lifecycle callback interfaces. Mostly useful for testing.

type Listener

type Listener func(*Event)

Listener is the signature for the func that needs to be implemented by the listener, e.g. the clickHandler etc.

type Modifier

type Modifier interface {
	Modify(element *Element)
}

A Modifier modifies an element, adding attributes, style or child elements etc.

func Aria

func Aria(name, val string) Modifier

Aria creates an accessibility attributes. See https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA

func CSS

func CSS(classes ...string) Modifier

CSS creates a CSS element with the provided classes. Note that duplicates are happily accepted.

func Data

func Data(name, val string) Modifier

Data creates a data attribute, e.g. data-columns="3" See https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Using_data_attributes

func Prop

func Prop(name string, value interface{}) Modifier

Prop adds a custom attribute.

func Style

func Style(name string, value interface{}) Modifier

Style adds a inline CSS style.

func Text

func Text(i interface{}) Modifier

Text creates a text element.

type Modifiers

type Modifiers []Modifier

Modifiers is used to Modify a list of elements (children).

func (Modifiers) Modify

func (mods Modifiers) Modify(e *Element)

Modify implements the Modifier interface.

type Option

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

Option is used to configure a component.

func Apply

func Apply(f func(o *js.Object) *js.Object) Option

Apply the func to the newly created React component.

func Export

func Export(name string) Option

Export is an option used to mark that the component should be exported to the JavaScript world as a Node.js module export.

func Global

func Global(name string) Option

Global is an option used to mark that the component should be exported to the JavaScript world as a global with the given name.

func WithConfig

func WithConfig(config ComponentConfig) Option

WithConfig adds optional static configuration to the component.

type Props

type Props map[string]interface{}

Props holds the React properties.

func (Props) Bool

func (p Props) Bool(key string) bool

Bool is convenience method to lookup a bool value from props.

func (Props) Call

func (p Props) Call(name string, args ...interface{}) *js.Object

Call calls a func with the given name in Props with the given args.

func (Props) Copy

func (p Props) Copy() Props

Copy creates a copy of this Props.

func (Props) Func

func (p Props) Func(name string) func(args ...interface{}) *js.Object

Func returns the func with the given name in Props.

func (Props) HasChanged

func (p Props) HasChanged(nextProps Props, keys ...string) bool

HasChanged reports whether the value of the property with any of the given keys has changed.

func (Props) Int

func (p Props) Int(key string) int

Int is convenience method to lookup a int value from props.

func (Props) Interface

func (p Props) Interface(key string) interface{}

Interface is a convenience method to lookup an interface value from props.

func (Props) String

func (p Props) String(key string) string

String is convenience method to lookup a bool value from props.

type ReactComponent

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

ReactComponent wraps a Facebook React component. This component can either be constructed from a Go implementation (see New) or loaded from JavaScript (see FromGlobal and Require).

func FromGlobal

func FromGlobal(path ...string) *ReactComponent

FromGlobal loads a React component from JavaScript's global object ("window" for browsers and "GLOBAL" for Node.js)

func New

func New(r Renderer, options ...Option) *ReactComponent

New creates a new Component given a Renderer and optional option(s). Note that the Renderer is the minimum interface that needs to be implemented, but New will perform interface upgrades for other lifecycle interfaces.

func NewSimpleComponent

func NewSimpleComponent(c Component, options ...Option) *ReactComponent

NewSimpleComponent can be used for quickly putting together components that only need to implement Renderer with no need of the owner (this) argument. Especially convenient for testing.

func Require

func Require(path ...string) *ReactComponent

Require loads a module the Node.js way. Note that this requires that the require function is present; if in the browser, and not in Node.js, try Browserify.

func (*ReactComponent) CloneElement

func (r *ReactComponent) CloneElement(props Props, children ...Component) *Element

CloneElement will, provided that an element has already been created for this component, clone that element with the original element's props with the new props merged in shallowly. New children will replace existing children. If this is the first invocation, a new element will be created. This may be be slightly faster when creating elements in a tight loop.

See https://facebook.github.io/react/docs/top-level-api.html#react.cloneelement

func (*ReactComponent) CreateElement

func (r *ReactComponent) CreateElement(props Props, children ...Component) *Element

CreateElement implements the Factory interface. TODO(bep) consolidate and clean

func (*ReactComponent) Node

func (r *ReactComponent) Node() *js.Object

Node implements the Component interface.

func (*ReactComponent) Render

func (r *ReactComponent) Render(elementID string, props Props)

Render the Component in the DOM with the given element ID and props.

type Refs

type Refs map[string]interface{}

Refs holds a reference to component references. See https://facebook.github.io/react/docs/more-about-refs.html

func (Refs) GetDOMNode

func (r Refs) GetDOMNode(key string) *js.Object

GetDOMNode returns the component from refs if it has been mounted into the DOM.

type Renderer

type Renderer interface {
	Render() Component
}

Renderer is the core interface used to render a Element.

func NewRenderer

func NewRenderer(renderFunc func() Component) Renderer

NewRenderer creates a Renderer with the provided func as the implementation.

func NewSimpleRenderer

func NewSimpleRenderer(c Component) Renderer

NewSimpleRenderer can be used for quickly putting together components that only need to implement Renderer with no need of the owner (this) argument.

type ShouldComponentUpdate

type ShouldComponentUpdate interface {
	ShouldComponentUpdate(next Cops) bool
}

ShouldComponentUpdate gets invoked before rendering when new props or state are being received. This is not called for the initial render or when forceUpdate is used.

type State

type State map[string]interface{}

State holds the React state.

func (State) Bool

func (s State) Bool(key string) bool

Bool is convenience method to lookup a bool value from state.

func (State) HasChanged

func (s State) HasChanged(nextState State, keys ...string) bool

HasChanged reports whether the value of the state with any of the given keys has changed. Note: This does only reference checking, so no deep equality. See https://github.com/gopherjs/gopherjs/issues/473

func (State) HasChangedDeeply

func (s State) HasChangedDeeply(nextState State, keys ...string) bool

HasChangedDeeply reports whether the value of the state with any of the given keys has changed. This uses reflect.DeepEqual. For shallow equality checking, see HasChanged.

func (State) Int

func (s State) Int(key string) int

Int is convenience method to lookup a int value from state.

func (State) Interface

func (s State) Interface(key string) interface{}

Interface is a convenience method to lookup an interface value from state.

func (State) String

func (s State) String(key string) string

String is convenience method to lookup a bool value from state.

type StateInitializer

type StateInitializer interface {
	GetInitialState() State
}

StateInitializer sets up the initial state.

type This

type This struct {
	This *js.Object
}

This is named for what it represents: The this context representation from the JavaScript side of the fence.

func NewThis

func NewThis(that *js.Object) *This

NewThis creates a new This based on a JavaScript object representation.

func (*This) Children

func (t *This) Children() *Children

Children returns this component's children, if any.

func (*This) Component

func (t *This) Component(name string) Modifier

Component returns a component stored in props by its name.

func (*This) Context

func (t *This) Context() Context

Context returns the context set; what you would expect to find in this.context in React.

func (*This) ForceUpdate

func (t *This) ForceUpdate()

ForceUpdate forces a re-render of the component.

func (*This) IsMounted

func (t *This) IsMounted() bool

IsMounted reports whether this component is mounted.

func (*This) Props

func (t *This) Props() Props

Props returns the properties set; this is what you would expect to find in this.props in React.

func (*This) Refs

func (t *This) Refs() Refs

Refs returns the component references. See https://facebook.github.io/react/docs/more-about-refs.html

func (*This) SetState

func (t *This) SetState(s State)

SetState sets the state with a map of Go interface{} values.

func (*This) SetThis

func (t *This) SetThis(that *js.Object)

SetThis implements the ThisSetter interface.

func (*This) State

func (t *This) State() State

State returns the state; what you would expect to find in this.properties in React.

type ThisSetter

type ThisSetter interface {
	SetThis(this *js.Object)
}

ThisSetter must be implemented by a component if JavaScript's this is needed. The simplest way of doing this is to just embed a This on the component struct.

Directories

Path Synopsis
Package attr defines markup to create HTML attributes supported by Facebook React.
Package attr defines markup to create HTML attributes supported by Facebook React.
Package el defines markup to create DOM elements.
Package el defines markup to create DOM elements.
Package evt defines markup to bind DOM events.
Package evt defines markup to bind DOM events.
Package tests contains tests.
Package tests contains tests.
grt
Package grt contains utilities used to test React components.
Package grt contains utilities used to test React components.

Jump to

Keyboard shortcuts

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