onthefly

package module
v1.2.3 Latest Latest
Warning

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

Go to latest
Published: Mar 17, 2022 License: BSD-3-Clause Imports: 8 Imported by: 8

README

On The Fly

Build Status GoDoc License Report Card

  • Package for generating HTML and CSS together, on the fly.
  • Can also be used for generating HTML, XML or CSS (or templates).
  • HTML and CSS can be generated together, but be presented as two seperate (but linked) files.
  • Could be used to set up a diskless webserver that generates all the content on the fly (something similar could also be achieved by using templates that are not stored on disk).

New/experimental features:

  • Generating WebGL graphics with Three.JS on the fly.
  • Generating AngularJS applications on the fly.

The SVG related code has been refactored out, optimized and moved to the tinysvg package.

Online API Documentation

godoc.org

Generate HTML, CSS and SVG in one go

Create hardware accelerated 3D-graphics with three.js

Experiment with AngularJS

Example for Negroni

package main

import (
    "fmt"
    "net/http"

    "github.com/urfave/negroni"
    "github.com/xyproto/onthefly"
    "github.com/xyproto/tinysvg"
)

// Generate a new SVG image
func svgImage() []byte {
    document, svg := tinysvg.NewTinySVG(128, 64)
    svg.Describe("Hello SVG")

    // x, y, radius, color
    svg.Circle(30, 10, 5, "red")
    svg.Circle(110, 30, 2, "green")
    svg.Circle(80, 40, 7, "blue")

    // x, y, font size, font family, text and color
    svg.Text(3, 60, 6, "Courier", "There will be cake", "#394851")

    return document.Bytes()
}

// Generate a new onthefly Page (HTML5 and CSS combined)
func indexPage(svgurl string) *onthefly.Page {

    // Create a new HTML5 page, with CSS included
    page := onthefly.NewHTML5Page("Demonstration")

    // Add some text
    page.AddContent(fmt.Sprintf("onthefly %.1f", onthefly.Version))

    // Change the margin (em is default)
    page.SetMargin(4)

    // Change the font family
    page.SetFontFamily("serif") // or: sans-serif

    // Change the color scheme
    page.SetColor("black", "#d0d0d0")

    // Include the generated SVG image on the page
    body, err := page.GetTag("body")
    if err == nil {
        // CSS attributes for the body tag
        body.AddStyle("font-size", "2em")
        body.AddStyle("font-family", "sans-serif")

        // Paragraph
        p := body.AddNewTag("p")

        // CSS style
        p.AddStyle("margin-top", "2em")

        // Image tag
        img := p.AddNewTag("img")

        // HTML attributes
        img.AddAttrib("src", svgurl)
        img.AddAttrib("alt", "Three circles")

        // CSS style
        img.AddStyle("width", "60%")
        img.AddStyle("border", "4px solid white")
    }

    return page
}

// Set up the paths and handlers then start serving.
func main() {
    fmt.Println("onthefly ", onthefly.Version)

    // Create a Negroni instance and a ServeMux instance
    n := negroni.Classic()
    mux := http.NewServeMux()

    // Publish the generated SVG as "/circles.svg"
    svgurl := "/circles.svg"
    mux.HandleFunc(svgurl, func(w http.ResponseWriter, req *http.Request) {
        w.Header().Add("Content-Type", "image/svg+xml")
        w.Write(svgImage())
    })

    // Generate a Page that includes the svg image
    page := indexPage(svgurl)
    // Publish the generated Page in a way that connects the HTML and CSS
    page.Publish(mux, "/", "/style.css", false)

    // Handler goes last
    n.UseHandler(mux)

    // Listen for requests at port 3000
    n.Run(":3000")
}

Example for net/http

package main

import (
    "fmt"
    "log"
    "net/http"
    "time"

    "github.com/xyproto/onthefly"
    "github.com/xyproto/tinysvg"
)

// Generate a new SVG image
func svgImage() []byte {
    document, svg := tinysvg.NewTinySVG(128, 64)
    svg.Describe("Hello SVG")

    // x, y, radius, color
    svg.Circle(30, 10, 5, "red")
    svg.Circle(110, 30, 2, "green")
    svg.Circle(80, 40, 7, "blue")

    // x, y, font size, font family, text and color
    svg.Text(3, 60, 6, "Courier", "There will be cake", "#394851")

    return document.Bytes()
}

// Generate a new onthefly Page (HTML5 and CSS combined)
func indexPage(svgurl string) *onthefly.Page {

    // Create a new HTML5 page, with CSS included
    page := onthefly.NewHTML5Page("Demonstration")

    // Add some text
    page.AddContent(fmt.Sprintf("onthefly %.1f", onthefly.Version))

    // Change the margin (em is default)
    page.SetMargin(4)

    // Change the font family
    page.SetFontFamily("serif") // or: sans-serif

    // Change the color scheme
    page.SetColor("black", "#d0d0d0")

    // Include the generated SVG image on the page
    body, err := page.GetTag("body")
    if err == nil {

        // CSS attributes for the body tag
        body.AddStyle("font-size", "2em")
        body.AddStyle("font-family", "sans-serif")

        // Paragraph
        p := body.AddNewTag("p")

        // CSS style
        p.AddStyle("margin-top", "2em")

        // Image tag
        img := p.AddNewTag("img")

        // HTML attributes
        img.AddAttrib("src", svgurl)
        img.AddAttrib("alt", "Three circles")

        // CSS style
        img.AddStyle("width", "60%")
        img.AddStyle("border", "4px solid white")
    }

    return page
}

// Set up the paths and handlers then start serving.
func main() {
    fmt.Println("onthefly ", onthefly.Version)

    // Create a mux
    mux := http.NewServeMux()

    // Publish the generated SVG as "/circles.svg"
    svgurl := "/circles.svg"
    mux.HandleFunc(svgurl, func(w http.ResponseWriter, req *http.Request) {
        w.Header().Add("Content-Type", "image/svg+xml")
        w.Write(svgImage())
    })

    // Generate a Page that includes the svg image
    page := indexPage(svgurl)

    // Publish the generated Page in a way that connects the HTML and CSS
    page.Publish(mux, "/", "/style.css", false)

    // Configure the HTTP server and permissionHandler struct
    s := &http.Server{
        Addr:           ":3000",
        Handler:        mux,
        ReadTimeout:    10 * time.Second,
        WriteTimeout:   10 * time.Second,
        MaxHeaderBytes: 1 << 20,
    }
    log.Println("Listening for requests on port 3000")

    // Start listening
    log.Fatal(s.ListenAndServe())
}

Additional screenshots

Screenshots from version 0.8:

TODO

  • Create a version 2 that is more focused on performance and has more consistent API function names.

Version, license and author

Documentation

Overview

onthefly can generate TinySVG, HTML and CSS on the fly

Index

Constants

View Source
const (
	Version = 1.2
)

Variables

This section is empty.

Functions

func AddBodyStyle

func AddBodyStyle(page *Page, bgimageurl string, stretchBackground bool)

AddBodyStyle styles the given page with a background image to the given page. Deprecated, use SetMarginAndBackgroundImage and also SansSerif instead.

func AddGoogleFonts

func AddGoogleFonts(page *Page, googleFonts []string)

AddGoogleFonts links to a given Google Font name

func AddHeader

func AddHeader(page *Page, js string)

Add javascript to the header and specify UTF-8 as the charset

func AddScriptToHeader

func AddScriptToHeader(page *Page, js string) error

Add JavaScript code in a script tag in the head tag Deprecated, use AddScriptToHead instead.

func Alert

func Alert(msg string) string

Alert returns JavaScript code that displays a pretty intruding message box. The "msg" will be quoted.

func DocumentReadyJS

func DocumentReadyJS(source string) string

Returns HTML that will run the given JavaScript code once the document is ready. Returns an empty string if there is no JavaScript code to run.

func Focus

func Focus(tagname string) string

Focus returns JavaScript code that sets focus on the given tag name

func Hide

func Hide(tagname string) string

Hide returns JavaScript code that hides the given tag name

func HideAnimated

func HideAnimated(tagname string) string

HideAnimated returns JavaScript code that hides the given tag name in an animated way

func HideIfNot

func HideIfNot(booleanURL, tagname string) string

HidIfNot returns JavaScript that will hide a tag if booleanURL doesn't return "1"

func JS

func JS(source string) string

JS wraps JavaScript code in a <script> tag

func Load

func Load(tagname, url string) string

Return JavaScript that loads the contents of the given URL into the given tag name

func NewThreeJS

func NewThreeJS(args ...string) (*Page, *Tag)

Create a HTML5 page that links with Three.JS and sets up a scene

func NewThreeJSWithGiven

func NewThreeJSWithGiven(titleText, js string) (*Page, *Tag)

Create a HTML5 page that includes the given JavaScript code at the end of the <body> tag, before </body>. The given JS code must be the contents of the http://threejs.org/build/three.min.js script for this to work.

func OnClick

func OnClick(tagname, source string) string

OnClick returns JavaScript code that runs the given JavaScript code when the given tag name is clicked on

func OnDocumentReady

func OnDocumentReady(source string) string

OnDocumentReady returns JavaScript code the runs the given JavaScript code when the HTML document is ready in the browser.

func Redirect

func Redirect(URL string) string

Redirect returns JavaScript code that redirects to the given URL

func SampleSVG1

func SampleSVG1() []byte

SampleSVG1 returns a drawing sample, #1

func SampleSVG2

func SampleSVG2() []byte

SampleSVG2 returns a drawing sample, #2

func SampleStar

func SampleStar(svg *tinysvg.Tag) error

SampleStar draws a star at the given position

func ScrollDownAnimated

func ScrollDownAnimated() string

ScrollDownAnimated returns JavaScript code that will slowly scroll the page down

func SetHTML

func SetHTML(tagname, html string) string

SetHTML returns JavaScript code that sets the HTML of the given tag name

func SetPixelPosition

func SetPixelPosition(tag *Tag, xpx, ypx int)

SetPixelPosition sets the absolute CSS position of a HTML tag

func SetRawValue

func SetRawValue(tagname, val string) string

SetRawValue returns JavaScript code that sets the contents of a given tag name, without quoting

func SetRelativePosition

func SetRelativePosition(tag *Tag, x, y string)

SetRelativePosition sets the relative CSS position of a HTML tag

func SetText

func SetText(tagname, text string) string

SetText returns JavaScript code that sets the text of the given tag name

func SetValue

func SetValue(tagname, val string) string

SetValue returns JavaScript code that quotes and then sets the contents of the given tag name

func SetWidthAndSide

func SetWidthAndSide(tag *Tag, width string, leftSide bool)

SetWidthAndSide sets the "width" and also "float: left" or "float: right"

func Show

func Show(tagname string) string

Show returns JavaScript code that shows the given tag name

func ShowAnimated

func ShowAnimated(tagname string) string

ShowAnimated returns JavaScript code that displays the given tag name in an animated way

func ShowAnimatedIf

func ShowAnimatedIf(booleanURL, tagname string) string

ShowAnimatedIf returns JavaScript that will show a tag if booleanURL returns "1"

func ShowInline

func ShowInline(tagname string) string

ShowInline returns JavaScript code that styles the given tag with "display:inline"

func ShowInlineAnimated

func ShowInlineAnimated(tagname string) string

ShowInlineAnimated returns JavaScript code that show the given tag with "display:inline", then hides it and then shows it in an animated way

func ShowInlineAnimatedIf

func ShowInlineAnimatedIf(booleanURL, tagname string) string

ShowInlineAnimatedIf returns JavaScript that shows the given tag in an animated way if the value from the given URL is "1"

func StandaloneTag

func StandaloneTag(tagname string) (*Page, *Tag)

StandaloneTag creates an empty page the only contains a tag with the given name. Returns both the Page and the Tag.

func TagString

func TagString(tagname string) string

TagString creates a new page with the given tag (name). The page is then returned as a string.

Types

type Element

type Element struct {
	ID string // name of the variable
	JS string // javascript code for creating the element
}

For Three.JS elements, like a mesh or material

type Geometry

type Geometry Element

Different types of elements

func NewBoxGeometry

func NewBoxGeometry(w, h, d int) *Geometry

Create geometry for a box

type Material

type Material Element

func NewMaterial

func NewMaterial(color string) *Material

Very simple type of material

func NewNormalMaterial

func NewNormalMaterial() *Material

Create a material which reflects the normals of the geometry

type Mesh

type Mesh Element

func NewMesh

func NewMesh(geometry *Geometry, material *Material) *Mesh

Create a new mesh, given geometry and material. The geometry and material will be instanciated together with the mesh.

type Page

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

func NewAngularPage

func NewAngularPage(titleText, angularVersion string) *Page

Create a blank HTML5 page that links with Angular.JS

func NewHTML5Page

func NewHTML5Page(titleText string) *Page

Create a blank HTML5 page

func NewPage

func NewPage(title, rootTagName string) *Page

NewPage creates a new XML/HTML/SVG page, with a root tag. If rootTagName contains "<" or ">", it can be used for preceding declarations, like <!DOCTYPE html> or <?xml version=\"1.0\"?>. Returns a pointer to a Page.

func SamplePage

func SamplePage(cssurl string) *Page

Sample OnTheFly-page (generates HTML5+CSS)

func (*Page) AddContent

func (page *Page) AddContent(content string) (*Tag, error)

AddContent adds content to the body tag. Returns the body tag and nil if successful. Returns and an error if no body tag is found, else nil.

func (*Page) AddScriptToBody

func (page *Page) AddScriptToBody(js string) (*Tag, error)

Add javascript code in a script tag at the end of the body tag

func (*Page) AddScriptToHead

func (page *Page) AddScriptToHead(js string) (*Tag, error)

Add javascript code in a script tag in the head tag

func (*Page) AddStyle

func (page *Page) AddStyle(s string) (*Tag, error)

AddStyle adds inline CSS to a page. Returns the style tag.

func (*Page) FullCanvas

func (page *Page) FullCanvas()

Prepare for a canvas/webgl tag that covers the entire page

func (*Page) GetCSS

func (page *Page) GetCSS() string

GetCSS renders CSS for a Page

func (*Page) GetHTML

func (page *Page) GetHTML() string

GetHTML renders HTML for a Page

func (*Page) GetRoot

func (page *Page) GetRoot() *Tag

GetRoot returns the root tag of the page

func (*Page) GetTag

func (page *Page) GetTag(name string) (*Tag, error)

GetTag searches all tags for the given name

func (*Page) GetXML

func (page *Page) GetXML(indent bool) string

GetXML renders XML for a Page

func (*Page) LinkToCSS

func (page *Page) LinkToCSS(cssurl string) error

Link a page up with a CSS file Takes the url to a CSS file as a string The given page must have a "head" tag for this to work Returns an error if no "head" tag is found, or nil

func (*Page) LinkToFavicon

func (page *Page) LinkToFavicon(favurl string) error

Link a page up with a Favicon file Takes the url to a favicon file as a string The given page must have a "head" tag for this to work Returns an error if no "head" tag is found, or nil

func (*Page) LinkToGoogleFont

func (page *Page) LinkToGoogleFont(name string) error

Link to Google Fonts

func (*Page) LinkToJS

func (page *Page) LinkToJS(jsURL string) error

Link a page up with a JS file Takes the url to a JS file as a string The given page must have a "head" tag for this to work Returns an error if no "head" tag is found, or nil

func (*Page) LinkToJSInBody

func (page *Page) LinkToJSInBody(jsURL string) (*Tag, error)

Link to JavaScript, at the end of the body

func (*Page) LinkToJSInHead

func (page *Page) LinkToJSInHead(jsURL string) (*Tag, error)

Link to JavaScript in the head

func (*Page) MetaCharset

func (page *Page) MetaCharset(charset string) error

Takes a charset, for example UTF-8, and creates a <meta> tag in <head>

func (*Page) NoScrollbars

func (page *Page) NoScrollbars() (*Tag, error)

Disable scrollbars. Needed when using "<!doctype html>" together with fullscreen canvas/webgl

func (*Page) Publish

func (page *Page) Publish(mux *http.ServeMux, htmlurl, cssurl string, refresh bool)

Publish the linked HTML and CSS for a Page. If refresh is true, the contents are generated every time. If refresh is false, the contents are cached.

func (*Page) SaveSVG

func (page *Page) SaveSVG(filename string) error

Save the current page as an SVG file

func (*Page) SetColor

func (page *Page) SetColor(fgColor string, bgColor string) (*Tag, error)

Set the foreground and background color of the body

func (*Page) SetFontFamily

func (page *Page) SetFontFamily(fontFamily string) (*Tag, error)

Set the font family

func (*Page) SetMargin

func (page *Page) SetMargin(em int) (*Tag, error)

Set the margins of the body

func (*Page) SetMarginAndBackgroundImage

func (page *Page) SetMarginAndBackgroundImage(imageURL string, stretchBackground bool)

SetMarginAndBackgroundImage sets a small margin of 1em and a given background image

func (*Page) String

func (page *Page) String() string

String renders the page as an HTML string

type RenderFunc

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

The Three.JS render function, where head and tail are standard

func NewRenderFunction

func NewRenderFunction() *RenderFunc

Create a new render function, which is called at every animation frame

func (*RenderFunc) AddJS

func (r *RenderFunc) AddJS(s string)

Add javascript code to the body of a render function

type SimpleWebHandle

type SimpleWebHandle (func(string) string)

Various function signatures for handling requests

type Tag

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

func NewTag

func NewTag(name string) *Tag

NewTag creates a new tag based on the given name. "name" is what will appear right after "<" when rendering as XML/HTML/SVG.

func (*Tag) AddAttrib

func (tag *Tag) AddAttrib(attrName, attrValue string)

AddAttrib adds an attribute to a tag, for instance "size" and "20"

func (*Tag) AddBox

func (tag *Tag) AddBox(id string, rounded bool, em, text, fgColor, bgColor, leftPadding string) *Tag

AddBox adds a <div> box

func (*Tag) AddCamera

func (three *Tag) AddCamera()

Add a camera with default settings

func (*Tag) AddChild

func (tag *Tag) AddChild(child *Tag)

AddChild adds a tag as a child to another tag

func (*Tag) AddContent

func (tag *Tag) AddContent(content string)

AddContent adds text to a tag. This is what will appear between two tag markers, for example: <tag>content</tag> If the tag contains child tags, they will be rendered after this content.

func (*Tag) AddImage

func (tag *Tag) AddImage(url string, width string) *Tag

Add an <img> image

func (*Tag) AddLastContent

func (tag *Tag) AddLastContent(content string)

AddLastContent appends content to the end of the exising content of a tag. Deprecated.

func (*Tag) AddNewTag

func (tag *Tag) AddNewTag(name string) *Tag

AddNewTag adds a new tag to another tag. This will place it one step lower in the hierarchy of tags. You can for example add a body tag to an html tag.

func (*Tag) AddRenderFunction

func (three *Tag) AddRenderFunction(r *RenderFunc, call bool)

Add a render function. If call is true, the render function is called at the end of the script.

func (*Tag) AddRenderer

func (three *Tag) AddRenderer()

Add a WebGL renderer with default settings

func (*Tag) AddSingularAttrib

func (tag *Tag) AddSingularAttrib(attrName string)

AddSingularAttrib adds attribute without a value

func (*Tag) AddStyle

func (tag *Tag) AddStyle(styleName, styleValue string)

AddStyle adds CSS tyle to a tag, for instance "background-color" and "red"

func (*Tag) AddTag

func (tag *Tag) AddTag(child *Tag)

AddTag adds a tag to another tag

func (*Tag) AddTestCube

func (three *Tag) AddTestCube() *Mesh

Add a test cube to the scene

func (*Tag) AddToScene

func (three *Tag) AddToScene(mesh *Mesh)

Add a mesh to the current scene

func (*Tag) AppendContent

func (tag *Tag) AppendContent(content string)

AppendContent appends content to the end of the exising content of a tag

func (*Tag) CameraPos

func (three *Tag) CameraPos(axis string, value int)

Set the camera position. Axis must be "x", "y", or "z".

func (*Tag) CountChildren

func (tag *Tag) CountChildren() int

CountChildren returns the number of children a tag has

func (*Tag) CountSiblings

func (tag *Tag) CountSiblings() int

CountSiblings returns the number of siblings a tag has

func (*Tag) CustomSansSerif

func (tag *Tag) CustomSansSerif(custom string)

CustomSansSerif styles the tag with some sort of sans-serif font, where a custom font can be given and put first in the list of fonts.

func (*Tag) GetAttrString

func (tag *Tag) GetAttrString() string

GetAttrString returns a string that represents all the attribute keys and values of a tag. This can be used when generating XML, SVG or HTML.

func (*Tag) GetCSS

func (tag *Tag) GetCSS() (ret string)

GetCSS renders CSS for a given tag

func (*Tag) GetChildren

func (tag *Tag) GetChildren() []*Tag

GetChildren returns all children for a given tag. Returns a slice of pointers to tags.

func (*Tag) GetTag

func (tag *Tag) GetTag(name string) (*Tag, error)

GetTag finds a tag by name and returns an error if not found. Returns the first tag that matches.

func (*Tag) LastChild

func (tag *Tag) LastChild() *Tag

LastChild returns the last child of a tag

func (*Tag) RepeatBackground

func (tag *Tag) RepeatBackground(bgimageurl, repeat string)

Repeat the background. repeat can be for instance "repeat-x"

func (*Tag) RoundedBox

func (tag *Tag) RoundedBox()

RoundedBox styles the tag as a box with a rounded border

func (*Tag) SansSerif

func (tag *Tag) SansSerif()

SansSerif styles the tag with some sort of sans-serif font

func (*Tag) SetColor

func (tag *Tag) SetColor(fgColor, bgColor string)

SetColor changes the forground and background color CSS styles

func (*Tag) SetMargin

func (tag *Tag) SetMargin(em int)

SetMargin sets a margin given in em on a tag

func (*Tag) SetRounded

func (tag *Tag) SetRounded(value string)

SetRounded applies rounded corners to an HTML tag

func (*Tag) SetRoundedEm

func (tag *Tag) SetRoundedEm(em int)

SetRoundedEm applies rounded corners to an HTML tag em is the roundedness, given as "em"

func (*Tag) String

func (tag *Tag) String() string

String gets HTML for a single Tag

type TemplateValues

type TemplateValues map[string]string

Directories

Path Synopsis
cmd

Jump to

Keyboard shortcuts

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