sht

package
v0.0.0-...-277be3d Latest Latest
Warning

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

Go to latest
Published: Sep 14, 2022 License: MIT Imports: 24 Imported by: 1

Documentation

Index

Constants

This section is empty.

Variables

View Source
var HtmlBooleanAttributes = map[string]bool{}
View Source
var HtmlVoidElements = map[string]bool{}

HtmlVoidElements Void elements are those that can't have any contents.

Functions

func CreateBoolMap

func CreateBoolMap(arr []string) map[string]bool

func CreateComponent

func CreateComponent(node *Node, attrs *Attributes, t *Compiler)

CreateComponent cria um componente. Um component é uma estrutura reutilizável que possui características especiais

func CreateNodeIdentifier

func CreateNodeIdentifier(sequence *Sequence) func(*Node) string

CreateNodeIdentifier creates a function that when invoked, adds a class so that a node can be identified

func HashMD5

func HashMD5(text string) string

HashMD5 computing the MD5 checksum of strings

func HashSha512Base64

func HashSha512Base64(content []byte) string

HashSha512Base64 return a base64-encoded cryptographic hash of a resource using SHA-512 hash algorithm

func HashXXH64

func HashXXH64(content []byte) string

HashXXH64 Make a fingerprint. Compute a non-cryptographic XXH64 checksum of strings

Encoded using Base64 URLSafe

func HashXXH64Hex

func HashXXH64Hex(text string) string

HashXXH64Hex computing the XXH64 checksum of strings

func HtmlEscape

func HtmlEscape(s string) string

func NormalizeName

func NormalizeName(name string) string

func TestCompile

func TestCompile(t *testing.T, template string, static []string, globalDirectives *Directives) (*Compiled, *Compiler)

TestCompile compiles a template and already tests the expected output

func TestRender

func TestRender(t *testing.T, compiled *Compiled, values map[string]interface{}, expected string) (*Rendered, *Scope)

TestRender renders a compiled and already tests the expected result

func TestTemplate

func TestTemplate(t *testing.T, template string, values map[string]interface{}, expected string, directives *Directives) (*Rendered, *Scope)

func TestUnindentedTemplate

func TestUnindentedTemplate(template string) string

Types

type Attribute

type Attribute struct {
	Name       string
	Value      string
	Namespace  string
	Normalized string // name normalized
}

Attribute representa um atributo html

func NewAttribute

func NewAttribute(name string, value string, namespace string) *Attribute

type Attributes

type Attributes struct {
	Map map[string]*Attribute
}

Attributes abstração dos atributos de um Node html

func (*Attributes) AddClass

func (a *Attributes) AddClass(value string)

AddClass Adds the specified class(es) to element

func (*Attributes) Clone

func (a *Attributes) Clone() *Attributes

Clone Uso interno, faz uma cópia dos atributos para ser usado em tempo de execução

func (*Attributes) Get

func (a *Attributes) Get(name string) (value string)

func (*Attributes) GetAttribute

func (a *Attributes) GetAttribute(name string) *Attribute

func (*Attributes) GetOrDefault

func (a *Attributes) GetOrDefault(name string, dfault string) (value string)

func (*Attributes) HasClass

func (a *Attributes) HasClass(value string) bool

HasClass Determine whether the element is assigned the given class.

func (*Attributes) Remove

func (a *Attributes) Remove(attr *Attribute)

func (*Attributes) RemoveClass

func (a *Attributes) RemoveClass(value string)

RemoveClass Remove a single class or multiple classes from element

func (*Attributes) Render

func (a *Attributes) Render() *Rendered

Render the attributes sorted by name. Boolean attributes (no value) are always rendered at the end

 &Rendered{
   Static: *[]string{
     ` attribute-one="`,
     `"  attribute-two="`,
     `" class="`,
     `" boolean-attr-one boolean-attr-2`,
   }
   Dynamics: []interface{}{
     "value-1",
     "value-2"
     "class-1 class-",
   }
}

func (*Attributes) Set

func (a *Attributes) Set(key string, value string)

type Compiled

type Compiled struct {
	Assets []*cmn.Asset // Reference to all resources that can be used by this compiled
	// contains filtered or unexported fields
}

Compiled structure representing a Compiled template

func Interpolate

func Interpolate(text string) (*Compiled, error)

Interpolate Compiles a string with markup into an interpolation function.

GO INTERPOLATION ( {value} or !{value} )

<element attribute="{return value}"> <element attribute="xpto {escape safe}"> <element attribute="xpto !{escape unsafe}"> <element attribute="!{escape unsafe}"> <element>{escape safe}</element> <element>!{escape unsafe}</element>

exp = Interpolate('Hello {name}!'); exp.Exec({name:'Syntax'}).String() == "Hello Syntax!"

func (*Compiled) Exec

func (c *Compiled) Exec(scope *Scope) *Rendered

Exec the rendering of the Compiled, applying the informed scope

func (*Compiled) Fingerprint

func (c *Compiled) Fingerprint() string

Fingerprint GetIndex static fingerprint

type Compiler

type Compiler struct {
	System     *TemplateSystem     // Reference to the instance that generated this TemplateSystem compiler
	Directives *Directives         // The directives registered to run in this build
	Assets     map[*cmn.Asset]bool // The possible resources that will be used by this template
	Context    *Context            // allows directives to save context information during compilation

	Sequence *Sequence
	// contains filtered or unexported fields
}

Compiler scope of html template being compiled

func NewCompiler

func NewCompiler(ts *TemplateSystem) *Compiler

func (*Compiler) Compile

func (c *Compiler) Compile(template string, filepath string) (*Compiled, error)

func (*Compiler) NextHash

func (c *Compiler) NextHash() string

NextHash Used by components to predictively obtain a hash

func (*Compiler) RegisterAsset

func (c *Compiler) RegisterAsset(asset *cmn.Asset)

RegisterAsset register an asset that can be used in this template

func (*Compiler) RegisterAssetJsContent

func (c *Compiler) RegisterAssetJsContent(content string) *cmn.Asset

RegisterAssetJsContent register an anonymous javascript that can be used in this template

func (*Compiler) RegisterAssetJsFilepath

func (c *Compiler) RegisterAssetJsFilepath(filepath string) (*cmn.Asset, error)

RegisterAssetJsFilepath register an existing javascript in the filesystem being used by this template

func (*Compiler) RegisterAssetJsURL

func (c *Compiler) RegisterAssetJsURL(src string) (*cmn.Asset, error)

RegisterAssetJsURL registers an external javascript being used by this template

func (*Compiler) SafeRemove

func (c *Compiler) SafeRemove(node *Node)

SafeRemove remove o node de forma segura

type Component

type Component struct {
}

Component a referencia para um componente

type ComponentFunc

type ComponentFunc func(scope *Scope)

type Context

type Context struct {
	Data   map[string]interface{}
	Timing *cmn.ServerTiming
}

Context simple framework for accessing the compile and run context.

Context can be used by directives to exchange or expose execution information

func NewContext

func NewContext() *Context

func (*Context) Get

func (s *Context) Get(key string) interface{}

Get some value from the context

func (*Context) GetOrDefault

func (s *Context) GetOrDefault(key string, dfault interface{}) interface{}

func (*Context) Set

func (s *Context) Set(key string, value interface{})

Set Save some data in context

type Directive

type Directive struct {
	Name string
	// When there are multiple Directives defined on a single HTML node, sometimes it is necessary to specify the order
	// in which the Directives are applied. The Priority is used to sort the Directives before their Compile functions
	// get called. Directive with greater numerical priority are compiled first. The default priority is 0.
	Priority int
	Restrict DirectiveRestrict
	// Quando possuir template, a diretiva é Terminal
	Template     string
	TemplatePath string
	// Assets e acesso ao fs.Sys, um diretório para permitir carregamento em tempo de compilação
	Assets fs.FS
	// true - transclude the transcludeSlots (i.e. the child nodes) of the directive's element.
	// 'element' - transclude the whole of the directive's element including any directives on this element that are
	// defined at a lower priority than this directive. When used, the template property is ignored.
	// {...} (an object hash): - map elements of the transcludeSlots onto transclusion "slots" in the template.
	Transclude interface{} // true, false, map[string]string
	// If set to true then the current priority will be the last set of Directives which will execute (any Directive at
	// the current priority will still execute as the order of execution on same priority is undefined).
	// Note that expressions and other Directive used in the directive's template will also be excluded from execution.
	// Quando a directiva é terminal:
	//  1. O Transclude fica disponível para o método Process
	//  2. O método Process pode retornar um *Rendered
	Terminal bool
	// false (default): No scope will be created for the directive. The directive will use its root's scope.
	// true: A new child scope that prototypically inherits from its root will be created for the directive's element.
	// If multiple Directives on the same element request a new scope, only one new scope is created.
	Scope      bool
	Compile    DirectiveCompileFunc
	Controller DirectiveControllerFunc
	Process    DirectiveProcessFunc
	Leave      DirectiveLeaveFunc
}

Directive @TODO: Salvar a referencia de todas as diretivas cadastradas, não permitir que a mesma diretiva seja redefinida ou recarregada. Sempre usar a mesma implementação existente em memória. Todas as diretivas que possuem conteúdo devem resultar em um Compiled

func (*Directive) Normalize

func (d *Directive) Normalize()

type DirectiveCompileFunc

type DirectiveCompileFunc func(node *Node, attrs *Attributes, c *Compiler) (*DirectiveMethods, error)

DirectiveCompileFunc uma funcão que visita um elemento html e pode realizar ajustes no template em tempo de compilação

type DirectiveControllerFunc

type DirectiveControllerFunc func(scope *Scope)

DirectiveControllerFunc função executada para permitir controlar

type DirectiveLeaveFunc

type DirectiveLeaveFunc func(scope *Scope)

DirectiveLeaveFunc função executada após a renderização do elemento associado a uma diretiva

type DirectiveLeaveInfo

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

type DirectiveMethods

type DirectiveMethods struct {
	Controller DirectiveControllerFunc
	Process    DirectiveProcessFunc
	Leave      DirectiveLeaveFunc
}

type DirectiveProcessFunc

type DirectiveProcessFunc func(scope *Scope, attr *Attributes, transclude TranscludeFunc) (rendered *Rendered)

DirectiveProcessFunc função executada antes da renderização do elemento associado a uma diretiva Quando a directiva é transclude, o conteúdo original é substituido em tempo de execução pelo Rendered retornado

type DirectiveProcessInfo

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

type DirectiveRestrict

type DirectiveRestrict uint8

DirectiveRestrict The directive must be found in specific location.

const (
	ELEMENT   DirectiveRestrict = 1 << iota // element name
	ATTRIBUTE                               // attribute
)

type Directives

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

Directives group the list of registered directives

func (*Directives) Add

func (d *Directives) Add(directive *Directive)

Add a new directive.

func (*Directives) Contains

func (d *Directives) Contains(directive *Directive) bool

Contains verifica se essa directiva já está registrada nessa lista

func (*Directives) NewChild

func (d *Directives) NewChild() *Directives

NewChild cria uma nova lista, que mantém referencia para a lista atual

type DirectivesByPriority

type DirectivesByPriority []*Directive

func (DirectivesByPriority) Len

func (l DirectivesByPriority) Len() int

func (DirectivesByPriority) Less

func (l DirectivesByPriority) Less(i, j int) bool

func (DirectivesByPriority) Swap

func (l DirectivesByPriority) Swap(i, j int)

type Dynamic

type Dynamic interface {
	// Exec a function that takes a scope argument, and returns a list of dynamic content.
	// @return nil, string, *Compiled, *Rendered
	Exec(scope *Scope) interface{}
}

Dynamic represents a dynamic part of a Compiled

type DynamicCompiled

type DynamicCompiled struct {
	Compiled *Compiled
}

DynamicCompiled um dynamic que apenas executa um compiled

func (*DynamicCompiled) Exec

func (d *DynamicCompiled) Exec(scope *Scope) interface{}

type DynamicDirectives

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

DynamicDirectives parte dinamica que executa as diretivas de um Node

func (*DynamicDirectives) Exec

func (nd *DynamicDirectives) Exec(scope *Scope) interface{}

type DynamicFunc

type DynamicFunc func(scope *Scope) interface{}

DynamicFunc permite usar uma função como um Dynamic

func (DynamicFunc) Exec

func (f DynamicFunc) Exec(scope *Scope) interface{}

type DynamicInterpolate

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

DynamicInterpolate parte dinamica de execução de uma expressão

func (*DynamicInterpolate) Exec

func (d *DynamicInterpolate) Exec(scope *Scope) interface{}

type DynamicInterpolateEscaped

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

DynamicInterpolateEscaped parte dinamica de execução de uma expressão

func (*DynamicInterpolateEscaped) Exec

func (d *DynamicInterpolateEscaped) Exec(scope *Scope) interface{}

type Expression

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

func ParseExpression

func ParseExpression(exp string) (*Expression, error)

ParseExpression process a single expression

func (*Expression) EvalBool

func (e *Expression) EvalBool(scope *Scope) bool

func (*Expression) EvalString

func (e *Expression) EvalString(scope *Scope) string

func (*Expression) Exec

func (e *Expression) Exec(scope *Scope) interface{}

type Live

type Live struct {
}

Live interface de inter

type Node

type Node struct {
	Parent, FirstChild, LastChild, PrevSibling, NextSibling *Node

	Type       NodeType
	Data       string
	DataAtom   atom.Atom
	Namespace  string
	Attributes *Attributes
	//AttrList   []*Attribute
	File   string
	Line   int
	Column int
}

A Node consists of a NodeType and some Data (tag name for element nodes, content for text) and are part of a tree of Nodes. Element nodes may also have a Namespace and contain a slice of Attributes. Data is unescaped, so that it looks like "a<b" rather than "a&lt;b". For element nodes, DataAtom is the atom for Data, or zero if Data is not a known tag name.

An empty Namespace implies a "http://www.w3.org/1999/xhtml" namespace. Similarly, "math" is short for "http://www.w3.org/1998/Math/MathML", and "svg" is short for "http://www.w3.org/2000/svg".

func Parse

func Parse(template string, filepath string) ([]*Node, error)

Parse returns the parse tree for the HTML from the given content.

The input is assumed to be UTF-8 encoded.

func (*Node) AppendChild

func (n *Node) AppendChild(c *Node)

AppendChild adds a node c as a child of n.

It will panic if c already has a parent or siblings.

func (*Node) DebugTag

func (n *Node) DebugTag() string

DebugTag Returns the string representation of the element.

func (*Node) ExtractChildren

func (n *Node) ExtractChildren() *Node

ExtractChildren returns a new parent to the children of the current node

func (*Node) GetChildNodes

func (n *Node) GetChildNodes() []*Node

GetChildNodes returns a collection (list) of an elements's child nodes.

func (*Node) Remove

func (n *Node) Remove()

Remove remove this node from parent node

func (*Node) RemoveChild

func (n *Node) RemoveChild(c *Node)

RemoveChild removes a node c that is a child of n. Afterwards, c will have no parent and no siblings.

It will panic if c's parent is not n.

func (*Node) Render

func (n *Node) Render() (string, error)

Render renders the parse tree n to string.

func (*Node) ReplaceByText

func (n *Node) ReplaceByText() *Node

ReplaceByText used for element transclude, replace current element with plain text, extracting all node data to a separate element

func (*Node) Transverse

func (n *Node) Transverse(callback func(node *Node) (stop bool))

Transverse run callback for node and all its children, until callback returns true

@TODO: Alterar o algoritmo para o formato enter() exit(). node.transverse(func(enter){ /*before*/ enter() /*after*/ })

type NodeType

type NodeType uint32

A NodeType is the type of a Node.

const (
	ErrorNode NodeType = iota
	TextNode
	DocumentNode
	ElementNode
	CommentNode
	DoctypeNode
	// RawNode nodes are not returned by the parser, but can be part of the
	// Node tree passed to func Render to insert raw HTML (without escaping).
	// If so, this package makes no guarantee that the rendered HTML is secure
	// (from e.g. Cross Site Scripting attacks) or well-formed.
	RawNode
)

type RegexMatch

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

func RegexExecAll

func RegexExecAll(re *regexp.Regexp, input string) []*RegexMatch

type Rendered

type Rendered struct {
	Static      *[]string     `json:"s"` // a list of literal strings
	Dynamics    []interface{} `json:"d"` // nil, string, Rendered
	Fingerprint string        `json:"f"`
	Root        bool          `json:"r"`
	Assets      []string      `json:"a"` // all the resources needed by that part
}

Rendered structure of a Compiled

func (*Rendered) String

func (r *Rendered) String() string

String convert the result to string

func (*Rendered) Write

func (r *Rendered) Write(buffer *bytes.Buffer)

Write the output to the given buffer

type Scope

type Scope struct {
	Context *Context // allows directives to save context information during execution
	// contains filtered or unexported fields
}

func NewRootScope

func NewRootScope() *Scope

func (*Scope) Destroy

func (s *Scope) Destroy()

func (*Scope) Fetch

func (s *Scope) Fetch(key interface{}) interface{}

Fetch used by expressions https://github.com/antonmedv/expr/blob/master/docs/Optimizations.md#reduced-use-of-reflect

func (*Scope) Get

func (s *Scope) Get(key string) (value interface{}, exists bool)

Get a value from scope or parent scope

func (*Scope) New

func (s *Scope) New(isolate bool) *Scope

New Creates a new child scope

The parent scope will propagate change events

func (*Scope) Set

func (s *Scope) Set(key string, value interface{})

Set a value in scope

type Sequence

type Sequence struct {
	Salt string
	// contains filtered or unexported fields
}

Sequence identifier generator utility qeu ensures that all executions have the same result

func (*Sequence) NextHash

func (s *Sequence) NextHash() string

func (*Sequence) NextInt

func (s *Sequence) NextInt() int

type StringSet

type StringSet map[string]bool

func (StringSet) Clone

func (p StringSet) Clone(others ...string) StringSet

func (StringSet) Contains

func (p StringSet) Contains(key string) (exists bool)

type TemplateSystem

type TemplateSystem struct {
	Loader     func(filepath string) (string, error)
	Directives *Directives
	Assets     map[*cmn.Asset]bool // All Assets that referenced in this system
}

func (*TemplateSystem) Compile

func (s *TemplateSystem) Compile(filepath string) (*Compiled, *Context, error)

func (*TemplateSystem) Load

func (s *TemplateSystem) Load(filepath string) (string, error)

Load load an html file

func (*TemplateSystem) NewScope

func (s *TemplateSystem) NewScope() *Scope

NewScope creates a new scope that can be used to render a compiled

func (*TemplateSystem) Register

func (s *TemplateSystem) Register(directives ...*Directive)

Register a global directive

func (*TemplateSystem) RegisterAsset

func (s *TemplateSystem) RegisterAsset(asset *cmn.Asset)

RegisterAsset register an asset

func (*TemplateSystem) RegisterAssetJsContent

func (s *TemplateSystem) RegisterAssetJsContent(content string) *cmn.Asset

RegisterAssetJsContent register an anonymous javascript

func (*TemplateSystem) RegisterAssetJsFilepath

func (s *TemplateSystem) RegisterAssetJsFilepath(filepath string) (*cmn.Asset, error)

RegisterAssetJsFilepath registers an existing javascript on the filesystem being used by this system

func (*TemplateSystem) RegisterAssetJsURL

func (s *TemplateSystem) RegisterAssetJsURL(src string) (*cmn.Asset, error)

RegisterAssetJsURL register an javascript asset by url

type TranscludeFunc

type TranscludeFunc func(slot string, preRender func(scope *Scope)) *Rendered

TranscludeFunc função disponível no método Process quando a directiva possui transclude

Jump to

Keyboard shortcuts

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