Documentation
¶
Overview ¶
Package onehtml parses HTML exactly as a browser does and gives the result as a read-only document tree.
The parser is the WHATWG HTML standard's: the tokenizer state machine and the tree construction algorithm in full, including fragments with a context element, foreign content (SVG and MathML), templates, the adoption agency algorithm and foster parenting. Whatever the bytes, the result is the tree a browser builds; malformed markup is not an error. Parse errors the standard lists are recorded in Document.Errors. The encoding is found as the Encoding Standard says: byte order mark, transport label (WithEncoding), then a prescan of <meta> declarations, with a restart if the parse finds one late.
Two layers ¶
The happy path is Parse (or ParseBytes) followed by the methods of Node:
doc, err := onehtml.Parse(r)
if err != nil { ... }
for n := range doc.Body().Descendants() {
if n.Is("a") { href, _ := n.Get("href"); ... }
}
html := doc.Body().InnerHTML()
The low level is the same data seen closely: every Node and Attr knows its byte range in the original input (Node.Span, Node.StartTagSpan, Attr.Span, Attr.ValueSpan), which quote an attribute used, and whether the parser made it up (an implied tbody, a reparented misnested element). Document.Source is the input as given and Document.SourceOffset maps an offset in the decoded text back to it. NewTokenizer runs the tokenizer alone, and Document.Errors lists parse errors with their positions.
Nodes ¶
A Node is a small value: a document pointer and an index into the document's node arena. Copy it freely; the zero Node is invalid and every method of it is safe, returning zero values. Nodes stay valid as long as the document is reachable. Traversals (Node.Children, Node.Descendants, Node.Ancestors) are iter.Seq values and use no recursion, so depth of the document cannot exhaust the stack.
Element and attribute names of HTML elements are lower case, SVG and MathML names have the case the standard's adjustment tables give them. Comparisons the standard defines as ASCII case-insensitive (Node.Attribute, Node.Is) fold ASCII only.
Editing ¶
A Document never changes. Document.Apply takes a list of Edit values (set or remove an attribute, replace text, insert, append, prepend, wrap, unwrap, replace or remove nodes, with markup parsed in the target's context) and returns a new snapshot, or fails with an *EditError and applies nothing. Document.Edit returns an Editor for building edits up node by node and committing them. A commit copies the node records (one memory copy) and shares everything else with the snapshot before it: the source, the decoded text, the source map and the attribute records. Handles into an older snapshot go on reading that snapshot. Each commit returns a ChangeSet: the net added, removed, moved, re-parented, re-attributed and re-texted nodes, with the attributes that differ, and the ranges of the original input the edits made stale. Surviving nodes keep their Node.Index, so a consumer can carry per-node results across snapshots. Edited nodes keep their original source ranges; Node.Edited and Node.Moved say where the tree no longer matches them.
The Editor also has the DOM's mutation methods: create nodes and fragments, clone, parse markup in a context, Editor.AppendChild and its relatives (fragments give their children), Editor.ReplaceChildren, class and attribute toggles. A refusal is an *EditError whose Kind names the DOM error, and nothing changes. ChangeSet.Merge joins consecutive commits into their net effect, and ChangeSet.Impact says whether a commit touches attributes, structure, text or style sheets.
Lossless editing ¶
Rewrite makes a list of edits and writes the result as bytes. Every edit becomes a splice at the bytes it touches in the original input, so quoting, case, entities, comments, line endings, a byte order mark and malformed markup elsewhere come back exactly as they were; with no edits the output is the input. Inserted text is written in the document's own encoding (a character the encoding lacks becomes a character reference in text and attribute values, and makes an edit of raw text, such as a script, invalid) and in the style the neighbouring markup uses. Every splice is checked by parsing the output: if it does not give the tree the edits should have made, the nearest enclosing element is rewritten from the expected tree instead (EditedRange.Level says so), and an edit nothing can express is EditFailed. A transaction applies all of its edits or none; each edit has its own EditOutcome and a reason.
Stylesheets are edited the same way. ParseStylesheet reads a linked sheet the caller supplies (the library never fetches one), Document.Stylesheets gives the <style> elements, and SetDeclaration, RemoveDeclaration, InsertRuleAfter, AppendRule, RemoveRule and ReplaceRule address rules and declarations. SetStyle and RemoveStyle edit a style attribute.
Edits can be saved and replayed. ReadEditFile and MarshalEditFile read and write the JSON edit format (bounded by EditLimits); each saved target carries a locator, a fingerprint and optionally the byte range it had. Replay finds every target again, applies what resolves and reports what does not: stale (gone or changed), ambiguous (several matches), invalid or failed. Nothing is guessed. NewLocatorIndex and ElementFingerprint make the targets to save.
Hostile input ¶
No input makes the parser panic or run unboundedly. Limits bound input size, nesting depth, attributes per tag, node count and recorded errors; they are checked before the work they guard, and exceeding one makes the parse fail with a *LimitError (which matches ErrLimit with errors.Is). The css and encoding packages return their own LimitError with the same fields, and their ErrLimit is this one. Nothing is fetched and no script is run: scripts are inert text.
Selectors ¶
Node.Select, Node.Matches and Node.Closest take Selectors Level 4 text; CompileSelector compiles it once for reuse, and Matcher is the low-level interface the cascade drives. Matching follows HTML (ASCII case-insensitive type and attribute names, the HTML pseudo-classes such as :checked, :disabled, :lang(), :dir() and :valid) and never recurses on document depth. :hover, :focus and the other interaction states match only when the caller supplies them with WithState.
The cascade ¶
Document.Style computes CSS for the document: the HTML standard's default style sheet, <style> elements, linked sheets the caller supplies (WithStylesheets), @import, style attributes and presentational hints, with origins, !important, @layer, specificity, CSS Nesting, @scope, @media under a StyleContext, @supports and custom properties. Styles.ComputedStyle gives the values getComputedStyle would; Styles.MatchedRules shows which rules matched. There is no layout: values that need it (a percentage width) stay as specified and @container never matches.
Serialization ¶
Node.OuterHTML and Node.InnerHTML implement the standard's HTML fragment serialization algorithm.
Example (QuickStart) ¶
Parse a page, select elements, read their computed style and change one of them without touching any other byte.
package main
import (
"fmt"
"log"
"strings"
"recursiveai.org/go/onehtml"
)
func main() {
doc, err := onehtml.Parse(strings.NewReader(`<style>a { color: green }</style>
<nav><a href="https://example.com/">Home</a></nav>`))
if err != nil {
log.Fatal(err)
}
links, err := doc.Select("nav a[href^='https://']")
if err != nil {
log.Fatal(err)
}
styles := doc.Style()
for _, a := range links {
href, _ := a.Get("href")
fmt.Println(a.TextContent(), href, styles.ComputedStyle(a).Get("color"))
}
res := onehtml.Rewrite(doc, []onehtml.Edit{onehtml.SetAttribute(links[0], "rel", "noopener")})
if !res.Applied() {
log.Fatal(res.Reasons)
}
fmt.Println(string(res.Document))
}
Output: Home https://example.com/ rgb(0, 128, 0) <style>a { color: green }</style> <nav><a href="https://example.com/" rel="noopener">Home</a></nav>
Index ¶
- Constants
- Variables
- func IsGeneratedName(name string) bool
- func MarshalEditFile(f *EditFile, opts ...MarshalOption) []byte
- func NormalizeText(s string) string
- type Anchor
- type Attr
- func (a Attr) Edited() bool
- func (a Attr) HasValue() bool
- func (a Attr) Name() string
- func (a Attr) NameSpan() Span
- func (a Attr) Namespace() Namespace
- func (a Attr) QualifiedName() string
- func (a Attr) Quote() byte
- func (a Attr) Span() Span
- func (a Attr) Valid() bool
- func (a Attr) Value() string
- func (a Attr) ValueSpan() Span
- type AttrChange
- type AttrQuote
- type Change
- type ChangeKind
- type ChangeSet
- type ComputedStyle
- func (c *ComputedStyle) CustomNames() []string
- func (c *ComputedStyle) DeclaredProperties() []string
- func (c *ComputedStyle) Get(name string) string
- func (c *ComputedStyle) InvalidDeclarations() []InvalidDeclaration
- func (c *ComputedStyle) Source(name string) (Source, bool)
- func (c *ComputedStyle) SpecifiedDisplay() string
- type Contrast
- type Declaration
- type DiagKind
- type DoctypeInfo
- type Document
- func Parse(r io.Reader, opts ...ParseOption) (*Document, error)
- func ParseBytes(b []byte, opts ...ParseOption) (*Document, error)
- func ParseFragment(r io.Reader, ctx FragmentContext, opts ...ParseOption) (*Document, error)
- func ParseFragmentBytes(b []byte, ctx FragmentContext, opts ...ParseOption) (*Document, error)
- func (d *Document) Apply(edits ...Edit) (*Document, *ChangeSet, error)
- func (d *Document) Body() Node
- func (d *Document) Doctype() Node
- func (d *Document) DocumentElement() Node
- func (d *Document) Edit(opts ...EditorOption) *Editor
- func (d *Document) ElementByID(id string) Node
- func (d *Document) Encoding() string
- func (d *Document) ErrorCount() int
- func (d *Document) Errors() []ParseError
- func (d *Document) Generation() int
- func (d *Document) Head() Node
- func (d *Document) IsFragment() bool
- func (d *Document) Len() int
- func (d *Document) NodeAt(index int) Node
- func (d *Document) Nodes() iter.Seq[Node]
- func (d *Document) QuirksMode() QuirksMode
- func (d *Document) Root() Node
- func (d *Document) Scripting() bool
- func (d *Document) Select(sel string, opts ...QueryOption) ([]Node, error)
- func (d *Document) SelectFirst(sel string, opts ...QueryOption) (Node, error)
- func (d *Document) Source() []byte
- func (d *Document) SourceOffset(textOffset int) int
- func (d *Document) Style(opts ...StyleOption) *Styles
- func (d *Document) Stylesheets() []*Stylesheet
- func (d *Document) Text() []byte
- type DocumentPosition
- type DocumentRef
- type Edit
- func AppendHTML(el Node, html string) Edit
- func AppendRule(s *Stylesheet, css string) Edit
- func InsertHTMLAfter(n Node, html string) Edit
- func InsertHTMLBefore(n Node, html string) Edit
- func InsertRuleAfter(r Rule, css string) Edit
- func InsertRuleAtEndOf(r Rule, css string) Edit
- func InsertRuleBefore(r Rule, css string) Edit
- func PrependHTML(el Node, html string) Edit
- func RemoveAttribute(el Node, name string) Edit
- func RemoveDeclaration(r Rule, property string) Edit
- func RemoveNode(n Node) Edit
- func RemoveRule(r Rule) Edit
- func RemoveStyle(el Node, property string) Edit
- func ReplaceRule(r Rule, css string) Edit
- func ReplaceText(n Node, text string) Edit
- func ReplaceWithHTML(n Node, html string) Edit
- func SetAttribute(el Node, name, value string) Edit
- func SetDeclaration(r Rule, property, value string, important bool) Edit
- func SetStyle(el Node, property, value string, important bool) Edit
- func SetStyleKeepImportant(el Node, property, value string) Edit
- func Unwrap(el Node) Edit
- func WrapHTML(n Node, count int, html string) Edit
- type EditError
- type EditFile
- type EditFileOption
- type EditKind
- type EditLimits
- type EditOutcome
- type EditedRange
- type Editor
- func (e *Editor) AddClass(el Node, tokens ...string) error
- func (e *Editor) AppendChild(parent, child Node) error
- func (e *Editor) AppendHTML(el Node, html string) error
- func (e *Editor) Clone(n Node, deep bool) (Node, error)
- func (e *Editor) Commit() *ChangeSet
- func (e *Editor) CreateComment(data string) (Node, error)
- func (e *Editor) CreateElement(name string, ns Namespace) (Node, error)
- func (e *Editor) CreateFragment() (Node, error)
- func (e *Editor) CreateText(data string) (Node, error)
- func (e *Editor) Discard()
- func (e *Editor) Document() *Document
- func (e *Editor) HasPending() bool
- func (e *Editor) Import(n Node, deep bool) (Node, error)
- func (e *Editor) InsertBefore(parent, child, ref Node) error
- func (e *Editor) InsertHTMLAfter(n Node, html string) error
- func (e *Editor) InsertHTMLBefore(n Node, html string) error
- func (e *Editor) ParseFragment(html string, ctx Node) (Node, error)
- func (e *Editor) Pending() *Document
- func (e *Editor) PrependChild(parent, child Node) error
- func (e *Editor) PrependHTML(el Node, html string) error
- func (e *Editor) Remove(n Node) error
- func (e *Editor) RemoveAttribute(el Node, name string) error
- func (e *Editor) RemoveChild(parent, child Node) error
- func (e *Editor) RemoveClass(el Node, tokens ...string) error
- func (e *Editor) RemoveStyle(el Node, property string) error
- func (e *Editor) ReplaceChild(parent, child, old Node) error
- func (e *Editor) ReplaceChildren(parent Node, nodes ...Node) error
- func (e *Editor) ReplaceText(n Node, text string) error
- func (e *Editor) ReplaceWithHTML(n Node, html string) error
- func (e *Editor) SetAttribute(el Node, name, value string) error
- func (e *Editor) SetAttributeNS(el Node, ns Namespace, qname, value string) error
- func (e *Editor) SetInnerHTML(el Node, html string) error
- func (e *Editor) SetStyle(el Node, property, value string, important bool) error
- func (e *Editor) ToggleAttribute(el Node, name string, force ...bool) (bool, error)
- func (e *Editor) ToggleClass(el Node, token string, force ...bool) (bool, error)
- func (e *Editor) Unwrap(el Node) error
- func (e *Editor) WrapHTML(n Node, count int, html string) error
- type EditorLimits
- type EditorOption
- type Fingerprint
- type FingerprintMatch
- type FocusSource
- type FontMetrics
- type FontMetricsFunc
- type FontQuery
- type FormKind
- type FormStates
- func (f FormStates) Get(n Node, kind FormKind) (value, ok bool)
- func (f FormStates) Len() int
- func (f FormStates) WithChecked(n Node, v bool) FormStates
- func (f FormStates) WithDisabled(n Node, v bool) FormStates
- func (f FormStates) WithIndeterminate(n Node, v bool) FormStates
- func (f FormStates) Without(n Node, kind FormKind) FormStates
- type FormatError
- type FragmentContext
- type InteractionState
- type InternalError
- type InvalidDeclaration
- type KeyframeBlock
- type KeyframeDeclaration
- type KeyframeValue
- type KeyframesRule
- type LimitError
- type Limits
- type LocatorIndex
- type MarshalOption
- type MatchedRule
- type MatchedStyleDeclaration
- type Matcher
- type Namespace
- type Node
- func (n Node) Ancestors() iter.Seq[Node]
- func (n Node) AnchorSpan() Span
- func (n Node) AppendInnerHTML(dst []byte) []byte
- func (n Node) AppendOuterHTML(dst []byte) []byte
- func (n Node) AttrCount() int
- func (n Node) Attribute(name string) (Attr, bool)
- func (n Node) AttributeNS(ns Namespace, local string) (Attr, bool)
- func (n Node) Attrs() iter.Seq[Attr]
- func (n Node) ChildElementCount() int
- func (n Node) ChildElements() iter.Seq[Node]
- func (n Node) Children() iter.Seq[Node]
- func (n Node) ClassName() string
- func (n Node) Classes() iter.Seq[string]
- func (n Node) Closest(sel string, opts ...QueryOption) (Node, error)
- func (n Node) ComparePosition(o Node) DocumentPosition
- func (n Node) Contains(o Node) bool
- func (n Node) Data() string
- func (n Node) DataSpan() Span
- func (n Node) DescendantElements() iter.Seq[Node]
- func (n Node) Descendants() iter.Seq[Node]
- func (n Node) Doctype() (DoctypeInfo, bool)
- func (n Node) Document() *Document
- func (n Node) Edited() bool
- func (n Node) ElementsByClassName(names string) iter.Seq[Node]
- func (n Node) ElementsByTagName(name string) iter.Seq[Node]
- func (n Node) ElementsByTagNameNS(uri, local string) iter.Seq[Node]
- func (n Node) EndTagSpan() Span
- func (n Node) FirstChild() Node
- func (n Node) FirstElementChild() Node
- func (n Node) Get(name string) (string, bool)
- func (n Node) Has(name string) bool
- func (n Node) HasClass(token string) bool
- func (n Node) ID() string
- func (n Node) Index() int
- func (n Node) InnerHTML() string
- func (n Node) Is(name string) bool
- func (n Node) IsConnected() bool
- func (n Node) IsElement() bool
- func (n Node) Kind() NodeKind
- func (n Node) LastChild() Node
- func (n Node) LastElementChild() Node
- func (n Node) Matches(sel string, opts ...QueryOption) (bool, error)
- func (n Node) Moved() bool
- func (n Node) Name() string
- func (n Node) Namespace() Namespace
- func (n Node) NextElementSibling() Node
- func (n Node) NextSibling() Node
- func (n Node) OuterHTML() string
- func (n Node) PITarget() string
- func (n Node) Parent() Node
- func (n Node) PrevElementSibling() Node
- func (n Node) PrevSibling() Node
- func (n Node) Provenance() Provenance
- func (n Node) Reparented() bool
- func (n Node) RootNode() Node
- func (n Node) Select(sel string, opts ...QueryOption) ([]Node, error)
- func (n Node) SelectFirst(sel string, opts ...QueryOption) (Node, error)
- func (n Node) SelfClosing() bool
- func (n Node) Span() Span
- func (n Node) StartTagSpan() Span
- func (n Node) Synthetic() bool
- func (n Node) TagName() string
- func (n Node) TemplateContent() Node
- func (n Node) TextContent() string
- func (n Node) Valid() bool
- func (n Node) WriteHTML(w io.Writer) error
- type NodeKind
- type Origin
- type ParseError
- type ParseOption
- type PointerKind
- type PropertyRegistration
- type Provenance
- type QueryOption
- type QuirksMode
- type ReplayDetail
- type ReplayOption
- type ReplayResult
- type ResolvedKeyframe
- type ResolvedKeyframes
- type RewriteOption
- type RewriteResult
- type Rule
- type SavedEdit
- type SavedMember
- type Selector
- func (s *Selector) All(root Node, opts ...QueryOption) iter.Seq[Node]
- func (s *Selector) Closest(n Node, opts ...QueryOption) Node
- func (s *Selector) First(root Node, opts ...QueryOption) Node
- func (s *Selector) Len() int
- func (s *Selector) Matches(n Node, opts ...QueryOption) bool
- func (s *Selector) PseudoElement(i int) string
- func (s *Selector) Specificity(i int) Specificity
- func (s *Selector) String() string
- type SelectorLimitError
- type SelectorLimits
- type SelectorOption
- type SelectorSyntaxError
- type SheetInfo
- type SheetReport
- type SniffResult
- type Source
- type SourceKind
- type Span
- type Specificity
- type StyleContext
- type StyleDelta
- type StyleDiagnostic
- type StyleImpact
- type StyleLimits
- type StyleOption
- func WithBaseURL(u string) StyleOption
- func WithDeclarationFilter(f func(property, value string) bool) StyleOption
- func WithFontMetrics(f FontMetricsFunc) StyleOption
- func WithStyleContext(ctx StyleContext) StyleOption
- func WithStyleLimits(l StyleLimits) StyleOption
- func WithStylesheetResolver(r StylesheetResolver) StyleOption
- func WithStylesheets(sheets map[string]string) StyleOption
- func WithUserAgentStylesheet(on bool) StyleOption
- func WithUserStylesheet(css string) StyleOption
- type Styles
- func (s *Styles) ChangedKeyframes(prev *Styles) []string
- func (s *Styles) ComputedStyle(n Node) *ComputedStyle
- func (s *Styles) Context() StyleContext
- func (s *Styles) Diagnostics() []StyleDiagnostic
- func (s *Styles) InvalidDeclarations() iter.Seq2[Node, InvalidDeclaration]
- func (s *Styles) Keyframes(name string) (*KeyframesRule, bool)
- func (s *Styles) MatchedRules(n Node) []MatchedRule
- func (s *Styles) PseudoStyle(n Node, kind string) *ComputedStyle
- func (s *Styles) Registrations() []PropertyRegistration
- func (s *Styles) ResolveAnimations(n Node) []*ResolvedKeyframes
- func (s *Styles) ResolveKeyframes(n Node, name string) (*ResolvedKeyframes, bool)
- func (s *Styles) Restyle(cs *ChangeSet, opts ...StyleOption) (*Styles, error)
- func (s *Styles) Sheets() []SheetInfo
- func (s *Styles) WithContext(ctx StyleContext, opts ...StyleOption) *Styles
- type Stylesheet
- type StylesheetOption
- type StylesheetResolver
- type Target
- type Token
- type TokenAttr
- type TokenKind
- type Tokenizer
- type TokenizerState
Examples ¶
- Package (QuickStart)
- Attr.NameSpan
- Change.InlineStyle
- ChangeSet.Merge
- CompileComplexSelector
- CompileSelector
- ComputedStyle.Source
- ComputedStyle.SpecifiedDisplay
- Document.Apply
- Document.ElementByID
- Document.Errors
- Document.Select
- Document.Style
- Editor
- Editor.AppendChild
- Editor.ReplaceChildren
- Editor.SetInnerHTML
- Editor.ToggleAttribute
- Editor.ToggleClass
- FormStates
- FragmentContextOf
- Limits
- LocatorIndex
- LocatorIndex.Verify
- MarshalEditFile
- Matcher
- NewEditFile
- NewTokenizer
- Node.AttributeNS
- Node.ChildElements
- Node.Closest
- Node.ComparePosition
- Node.DataSpan
- Node.ElementsByClassName
- Node.ElementsByTagName
- Node.ElementsByTagNameNS
- Node.HasClass
- Node.Matches
- Node.Provenance
- Node.Select
- Node.Span
- Node.TagName
- Parse
- ParseFragmentBytes
- ParseStylesheet
- ReadEditFile
- Replay
- Rewrite
- Rewrite (Outcomes)
- Selector.All
- SetStyle
- SniffEncoding
- StyleContext
- StyleContext (Forms)
- Styles.ChangedKeyframes
- Styles.InvalidDeclarations
- Styles.Keyframes
- Styles.MatchedRules
- Styles.Registrations
- Styles.ResolveAnimations
- Styles.Restyle
- Styles.WithContext
- Tokenizer (Positions)
- WithDeclarationFilter
- WithEditorLimits
- WithEncoding
- WithFontMetrics
- WithState
- WithStyleLimits
- WithStylesheetResolver
- WithStylesheets
- WithTargetFragment
Constants ¶
const ( // LimitValue is the length in bytes of one attribute value or one text // node ([EditorLimits.MaxValueLength]). LimitValue = "value length" // LimitNames is the number of distinct element and attribute names the // document holds ([EditorLimits.MaxNames]). LimitNames = "names" )
Names of the limits an Editor adds to the ones of LimitError.
const ( // LimitInputSize is the size of the input in bytes ([Limits.MaxInputBytes], // [SelectorLimits.MaxInput]). LimitInputSize = "input size" // LimitDepth is the nesting depth of open elements ([Limits.MaxDepth]). LimitDepth = "depth" // LimitFormatting is the length of the list of active formatting // elements ([Limits.MaxFormattingElements]). LimitFormatting = "formatting elements" // LimitAttributes is the number of attributes of one tag // ([Limits.MaxAttributes]). LimitAttributes = "attributes" // LimitNodes is the number of nodes of a document ([Limits.MaxNodes]). LimitNodes = "nodes" // LimitTotalAttributes is the number of attributes in a whole document // ([Limits.MaxTotalAttributes]). LimitTotalAttributes = "total attributes" // LimitOffsetRuns is the size of the map from decoded text to input bytes // ([Limits.MaxOffsetRuns]). LimitOffsetRuns = "offset map runs" // LimitText is the size of the text an editor holds. LimitText = "text" // LimitSelectorNesting is how deep a selector nests // ([SelectorLimits.MaxNesting]). LimitSelectorNesting = "selector nesting" // LimitSelectorList is the number of complex selectors in a list // ([SelectorLimits.MaxSelectors]). LimitSelectorList = "selectors in a list" // LimitSelectorCompounds is the number of compound selectors in one // complex selector ([SelectorLimits.MaxCompounds]). LimitSelectorCompounds = "compounds in a selector" // LimitSelectorSimples is the number of simple selectors in one selector // ([SelectorLimits.MaxSimples]). LimitSelectorSimples = "simple selectors" )
The names a LimitError.Limit or SelectorLimitError.Limit can hold.
const (
// MaxImportDepth is how deep a chain of @import rules is followed.
MaxImportDepth = 16
)
Limits of the style sources.
Variables ¶
var ErrEdit = errors.New("onehtml: invalid edit")
ErrEdit is matched by errors.Is for every *EditError.
var ErrEditFormat = errors.New("onehtml: invalid edit file")
ErrEditFormat is matched by errors.Is for every *FormatError.
var ErrLimit = limit.Err
ErrLimit is matched by errors.Is for every LimitError.
The same value is css.ErrLimit and encoding.ErrLimit, so one check covers every package of the module.
var ErrSelectorLimit = errors.New("onehtml: selector limit exceeded")
ErrSelectorLimit is matched by errors.Is for a selector that exceeds one of the SelectorLimits (see SelectorLimitError).
var ErrSelectorSyntax = errors.New("onehtml: selector syntax error")
ErrSelectorSyntax is matched by errors.Is for every selector that is not valid Selectors Level 4 text (see SelectorSyntaxError).
var ErrStaleChanges = errors.New("onehtml: the change set does not start from the document of these styles")
ErrStaleChanges is returned by Styles.Restyle for a change set that does not start from the snapshot the styles were computed for.
Functions ¶
func IsGeneratedName ¶
IsGeneratedName reports whether a class name or id looks minted by a build tool, such as "Button_primary__3xK9z" or "css-1x2y3z". Locators never use such an id and fingerprints leave such names out. The name is cut into segments at every character that is not an ASCII letter or digit; it is generated when some segment of five or more characters is all digits, letters and digits with at least two changes between a digit and a non-digit, or ASCII letters of both cases that are not a run of camel-case words ("navLink" is not generated, "bdfBwQ" is).
func MarshalEditFile ¶
func MarshalEditFile(f *EditFile, opts ...MarshalOption) []byte
MarshalEditFile writes the envelope as compact JSON in the format's fixed member order. The same envelope always gives the same bytes: strings are escaped only as RFC 8259 requires plus the C0 controls; non-ASCII text, "<", ">", "&" and "'" are written as they are.
With WithEditFileIndent the same JSON value is written indented by two spaces per level, one member or array item per line; the format defines no layout, so only the value is the same.
Example ¶
MarshalEditFile and ReadEditFile are inverses: what was read is written back as compact JSON in the format's fixed member order.
package main
import (
"fmt"
"recursiveai.org/go/onehtml"
)
func main() {
file, _ := onehtml.ReadEditFile([]byte(`{ "version": 1, "format": "onehtml-edits",
"edits": [ {"op": "remove", "target": {"locator": "#gone"}} ] }`))
fmt.Println(string(onehtml.MarshalEditFile(file)))
}
Output: {"format":"onehtml-edits","version":1,"edits":[{"op":"remove","target":{"locator":"#gone"}}]}
func NormalizeText ¶
NormalizeText returns s as a fingerprint reads text: every run of ASCII white space (space, tab, line feed, form feed, carriage return) becomes one space and the ends are trimmed. Other characters, no-break space included, are left alone.
Types ¶
type Anchor ¶
Anchor is the source range of an element's start tag through its end, in bytes of the original input, and the hash of those bytes.
type Attr ¶
type Attr struct {
// contains filtered or unexported fields
}
Attr is a handle to an attribute of an element.
func (Attr) Edited ¶
Edited reports whether an edit gave the attribute a new value; the spans still describe the value in the source.
func (Attr) HasValue ¶
HasValue reports whether the source gave the attribute a value (as opposed to a bare name).
func (Attr) NameSpan ¶
NameSpan returns the byte range of the attribute's name as written in the source. It is absent for the zero Attr and for attributes without source.
Example ¶
package main
import (
"fmt"
"recursiveai.org/go/onehtml"
)
func main() {
src := `<p DATA-X = '1'>`
doc, _ := onehtml.ParseBytes([]byte(src))
a, _ := doc.Body().FirstChild().Attribute("data-x")
ns, vs := a.NameSpan(), a.ValueSpan()
fmt.Printf("%q %q\n", src[ns.Start:ns.End], src[vs.Start:vs.End])
}
Output: "DATA-X" "1"
func (Attr) Namespace ¶
Namespace returns the attribute's namespace: NoNamespace, or XLink, XML or XMLNS for the foreign attributes the standard adjusts.
func (Attr) QualifiedName ¶
QualifiedName returns the attribute's name with its prefix: "xlink:href", "xml:lang", "xmlns:xlink", "xmlns", or the plain name.
func (Attr) Quote ¶
Quote returns the quote character that delimited the value in the source, '"' or '\”, or 0.
func (Attr) Span ¶
Span returns the byte range of the whole attribute, name through the closing quote. It is absent for the zero Attr.
func (Attr) Valid ¶
Valid reports whether a refers to an attribute; the zero Attr is invalid and every method of it answers with an empty value.
type AttrChange ¶
type AttrChange struct {
// Name is the attribute's local name, and Namespace its namespace.
Name string
Namespace Namespace
// Old and New are the values; HadOld and HasNew say whether the
// attribute existed before and after.
Old, New string
HadOld, HasNew bool
}
AttrChange is one attribute that differs between two snapshots.
type AttrQuote ¶
type AttrQuote uint8
AttrQuote is how an attribute's value was written.
const ( // QuoteNone means the attribute had no "=" and no value. QuoteNone AttrQuote = iota // QuoteUnquoted means the value follows "=" without quotes; it may be // empty, as in "a=". QuoteUnquoted // QuoteSingle means the value is in single quotes. QuoteSingle // QuoteDouble means the value is in double quotes. QuoteDouble )
The ways a value is written.
type Change ¶
type Change struct {
// Node is the node: in the new snapshot, except for [ChangeRemoved],
// where it belongs to the old one.
Node Node
// Kind is the union of the ways the node changed.
Kind ChangeKind
// Attrs lists the attributes that differ, when Kind has
// [ChangeAttributes]: first those present in the new snapshot in their
// order, then those only the old one had.
Attrs []AttrChange
}
Change describes the net effect of a commit on one node.
func (Change) AttrChanged ¶
AttrChanged reports whether the attribute with the given local name (no namespace) differs. For an HTML element the name is compared ASCII case-insensitively.
func (Change) Classes ¶
Classes lists the class tokens a change added and removed, in the order they appear in the new and the old value of the class attribute. Both are empty unless the change has ChangeAttributes and the class token set differs (a change of white space only is none).
func (Change) Has ¶
func (c Change) Has(k ChangeKind) bool
Has reports whether the change includes every bit of k.
func (Change) InTemplate ¶
InTemplate reports whether the changed node is inside a template's contents. That content is inert: it is not part of the document's tree, so style and accessibility consumers can skip it (see ChangeSet.Impact).
func (Change) InlineStyle ¶
func (c Change) InlineStyle() []StyleDelta
InlineStyle lists the properties of the element's style attribute whose declared value changed, found by parsing the old and the new attribute value (the last declaration of a property wins; invalid declarations are ignored). Properties are listed in the order of the new value, then those only the old one declared. It is empty unless the change has ChangeAttributes and the style attribute changed.
Example ¶
InlineStyle lists the properties of a style attribute whose value changed.
package main
import (
"fmt"
"recursiveai.org/go/onehtml"
)
func main() {
doc, _ := onehtml.ParseBytes([]byte(`<p style="color: red; width: 1px">t</p>`))
ed := doc.Edit()
p := doc.Body().FirstChild()
_ = ed.SetStyle(p, "color", "blue", false)
_ = ed.RemoveStyle(p, "width")
for _, c := range ed.Commit().Changes {
for _, d := range c.InlineStyle() {
fmt.Printf("%s: %q -> %q\n", d.Property, d.Old, d.New)
}
}
}
Output: color: "red" -> "blue" width: "1px" -> ""
type ChangeKind ¶
type ChangeKind uint8
ChangeKind is a set of bits saying how a node changed in a commit.
const ( // ChangeAdded marks the root of a subtree that is in the new snapshot // and was not in the old one (inserted, or re-attached after being // detached). The nodes below it are implied. ChangeAdded ChangeKind = 1 << iota // ChangeRemoved marks the root of a subtree that was in the old // snapshot and is not in the new one. Its [Change.Node] belongs to the // old snapshot. The nodes below it are implied. ChangeRemoved // ChangeMoved marks a node that is in both snapshots and was placed // under another parent or after another sibling by an edit. ChangeMoved // ChangeChildren marks a node that is in both snapshots and whose list // of children differs. ChangeChildren // ChangeAttributes marks an element whose attributes differ; the // differences are in [Change.Attrs]. ChangeAttributes // ChangeText marks a text or comment node whose data differs. ChangeText )
The ways a node can change. A Change holds a union of them.
type ChangeSet ¶
type ChangeSet struct {
Old, New *Document
// Changes holds one entry per changed node, ordered by node index.
Changes []Change
// Affected lists the byte ranges of the original input (see
// [Document.Source]) that the commit makes stale: the ranges of removed
// and moved subtrees, of changed text nodes, and of the start tags of
// elements whose attributes changed. It is sorted, and ranges that
// overlap or touch are merged. Added content has no source and adds no
// range; where it goes is in the tree.
Affected []Span
}
ChangeSet is the net effect of one commit, as the cascade needs it to update incrementally (Styles.Restyle): precise about which nodes and attributes differ, with no entry for a node that ends where it began. A nil ChangeSet is empty.
Old and New are the snapshots before and after. Changes list nodes in index order. A subtree that was added or removed has one entry at its root; the nodes below are implied. A node that only has new children, or whose attributes or text changed, has an entry with the matching bits; whatever else the change reaches (descendants for inherited style, siblings for selectors such as :has(), + and ~) is for the consumer to derive from the tree, which it can read in both snapshots.
func (*ChangeSet) Impact ¶
func (c *ChangeSet) Impact() StyleImpact
Impact says which kinds of work the commit gives a style consumer. A nil or empty set has none, and so has one that only changed the inert contents of templates.
func (*ChangeSet) Merge ¶
Merge returns the net effect of two consecutive commits as one change set, from c.Old to next.New: a node inserted by one and removed by the other is not listed, several changes to one attribute are one with the first old and the last new value, a node removed and put back in place is not moved. Either set may be nil or empty. It fails with ErrStaleChanges when next does not start where c ends.
Example ¶
Merge joins consecutive commits into their net effect: the attribute changed twice is one change, from its first value to its last.
package main
import (
"fmt"
"recursiveai.org/go/onehtml"
)
func main() {
doc, _ := onehtml.ParseBytes([]byte(`<p class="a" title="x">t</p>`))
ed := doc.Edit()
p := doc.Body().FirstChild()
_ = ed.AddClass(p, "b")
_ = ed.SetAttribute(p, "title", "y")
first := ed.Commit()
p = ed.Document().NodeAt(p.Index())
_ = ed.SetAttribute(p, "title", "z")
_ = ed.RemoveClass(p, "a")
second := ed.Commit()
net, _ := first.Merge(second)
for _, c := range net.Changes {
added, removed := c.Classes()
fmt.Println("classes +", added, "-", removed)
for _, a := range c.Attrs {
if a.Name == "title" {
fmt.Printf("title %q -> %q\n", a.Old, a.New)
}
}
}
fmt.Println(net.Impact())
}
Output: classes + [b] - [a] title "x" -> "z" attributes
type ComputedStyle ¶
type ComputedStyle struct {
// contains filtered or unexported fields
}
ComputedStyle is the computed style of one element: the values getComputedStyle gives, as the CSSOM serializes them.
func (*ComputedStyle) CustomNames ¶
func (c *ComputedStyle) CustomNames() []string
CustomNames returns the names of the custom properties that have a value, sorted.
func (*ComputedStyle) DeclaredProperties ¶
func (c *ComputedStyle) DeclaredProperties() []string
DeclaredProperties returns the names of the properties some declaration set for this element, in the property table's order. Inherited and initial values are not listed; ComputedStyle.Get reads them all.
func (*ComputedStyle) Get ¶
func (c *ComputedStyle) Get(name string) string
Get returns the computed value of a property by its lower-case name ("background-color"), or of a custom property by its name with "--". Values that depend on layout (a width as a percentage of its container) stay as specified. A custom property that is unset or invalid, and an unknown property, give "".
func (*ComputedStyle) InvalidDeclarations ¶ added in v1.1.0
func (c *ComputedStyle) InvalidDeclarations() []InvalidDeclaration
InvalidDeclarations returns the declarations that won the cascade for the element and are invalid at computed-value time, each once, in the order of the property table and then of custom property names. A declaration that is invalid when it is parsed never takes part in the cascade and is not listed. The result is nil for a nil style or when there is none.
func (*ComputedStyle) Source ¶
func (c *ComputedStyle) Source(name string) (Source, bool)
Source reports where the computed value of the property (a longhand, by its lower-case name, or a custom property with its "--") came from: the declaration that won the cascade, or that it is inherited or the initial value. It reports false for an unknown property and for a shorthand, which has no value of its own.
The answer says which declaration supplied the value after the cascade; a value that is invalid at computed-value time (var() with no value) still names the declaration. The Selector is the rule's whole selector list.
Example ¶
package main
import (
"fmt"
"strings"
"recursiveai.org/go/onehtml"
)
func main() {
doc, _ := onehtml.Parse(strings.NewReader(`<style>@layer base { p { color: red } } p.note { margin-top: 3px }</style><p class=note id=p>x</p>`))
p, _ := doc.SelectFirst("#p")
cs := doc.Style().ComputedStyle(p)
for _, name := range []string{"color", "margin-top", "margin-left"} {
src, _ := cs.Source(name)
fmt.Printf("%s: initial=%v selector=%q layer=%q\n", name, src.Initial, src.Selector, src.Layer)
}
}
Output: color: initial=false selector="p" layer="base" margin-top: initial=false selector="p.note" layer="" margin-left: initial=true selector="" layer=""
func (*ComputedStyle) SpecifiedDisplay ¶ added in v1.1.1
func (c *ComputedStyle) SpecifiedDisplay() string
SpecifiedDisplay returns the element's display as declared, in the short form ComputedStyle.Get uses ("inline-flex", "table-cell", "block"), before the blockification a float, an absolutely positioned element, the root element or a flex or grid item gets (CSS Display 3 section 2.7). Get("display") reports the blockified value, so a float declared inline-flex reads "flex" there and "inline-flex" here, which is what a consumer needs to know its inner display type (flex, grid, table, flow-root, ...). Without any of those conditions the two agree. An inherited display is the parent's computed value, as the CSS-wide keyword defines it. A nil or zero ComputedStyle gives "".
Example ¶
A float computes to a block-level display, so Get("display") has lost the inner display type; SpecifiedDisplay keeps it.
package main
import (
"fmt"
"strings"
"recursiveai.org/go/onehtml"
)
func main() {
doc, _ := onehtml.Parse(strings.NewReader(
`<style>#f{float:left;display:inline-flex}</style><div id=f></div>`))
f, _ := doc.SelectFirst("#f")
cs := doc.Style().ComputedStyle(f)
fmt.Println(cs.Get("display"), cs.SpecifiedDisplay())
}
Output: flex inline-flex
type Declaration ¶
type Declaration struct {
// Name is as written (not case-folded), Value the source text of the
// value without surrounding white space or !important.
Name, Value string
Important bool
}
Declaration is one declaration of a rule.
type DiagKind ¶
type DiagKind uint8
DiagKind says what a StyleDiagnostic reports.
const ( // DiagMissingStylesheet: a linked or imported sheet the caller did not supply. DiagMissingStylesheet DiagKind = iota + 1 // DiagImportCycle: an @import that leads back to a sheet being imported. DiagImportCycle // DiagImportDepth: an @import chain deeper than [MaxImportDepth]. DiagImportDepth // DiagLimit: a count or size limit stopped some input from being read. DiagLimit // DiagUnsupportedRule: a rule the cascade does not apply (@container, an @scope inside @scope). DiagUnsupportedRule // DiagBadStylesheet: a sheet that could not be read at all. DiagBadStylesheet )
Diagnostic kinds.
type DoctypeInfo ¶
type DoctypeInfo struct {
Name string
PublicID, SystemID string
HasPublic, HasSystem bool
ForceQuirks bool
}
DoctypeInfo describes a doctype node.
type Document ¶
type Document struct {
// contains filtered or unexported fields
}
Document is a parsed HTML document or fragment. It owns the original bytes, the decoded text and a flat arena of node records, and is safe for concurrent reads.
Make one with Parse, ParseBytes or the fragment forms, or get one from Document.Apply or Editor.Commit. The zero Document and a nil *Document are not documents: they have no nodes, every method answers with an empty value (the zero Node, no errors, no source) and every edit is refused.
func Parse ¶
func Parse(r io.Reader, opts ...ParseOption) (*Document, error)
Parse reads all of r and parses it as an HTML document, as a browser does: the encoding is found from a byte order mark, the options or a <meta> declaration, and the tree is built by the HTML standard's parsing algorithm, whose error recovery accepts any input. Parse errors are recorded in Document.Errors and never fail the parse. Parse fails only when r is nil, reading r fails or the input exceeds a Limits limit.
Example ¶
The happy path: parse, walk, read.
package main
import (
"fmt"
"strings"
"recursiveai.org/go/onehtml"
)
func main() {
doc, err := onehtml.Parse(strings.NewReader(`<p class=intro>Hello <a href="/x">world</a>`))
if err != nil {
panic(err)
}
for n := range doc.Body().Descendants() {
if n.Is("a") {
href, _ := n.Get("href")
fmt.Println(n.TextContent(), href)
}
}
fmt.Println(doc.Body().InnerHTML())
}
Output: world /x <p class="intro">Hello <a href="/x">world</a></p>
func ParseBytes ¶
func ParseBytes(b []byte, opts ...ParseOption) (*Document, error)
ParseBytes is like Parse for input already in memory. The document keeps b; the caller must not modify it afterwards.
func ParseFragment ¶
func ParseFragment(r io.Reader, ctx FragmentContext, opts ...ParseOption) (*Document, error)
ParseFragment reads all of r as UTF-8 markup and parses it as the HTML fragment parsing algorithm does for the given context element. The returned document's root is a fragment node whose children are the parsed nodes.
func ParseFragmentBytes ¶
func ParseFragmentBytes(b []byte, ctx FragmentContext, opts ...ParseOption) (*Document, error)
ParseFragmentBytes is like ParseFragment for input already in memory.
Example ¶
A fragment is parsed in the context of an element, as innerHTML does.
package main
import (
"fmt"
"recursiveai.org/go/onehtml"
)
func main() {
ctx := onehtml.FragmentContext{Namespace: onehtml.HTML, Name: "tr"}
frag, _ := onehtml.ParseFragmentBytes([]byte("<td>1<td>2"), ctx)
fmt.Println(frag.Root().InnerHTML())
}
Output: <td>1</td><td>2</td>
func (*Document) Apply ¶
Apply makes the edits in order on a copy of d and returns the new snapshot with the net ChangeSet. All of them apply or none does: on the first refusal it returns an *EditError carrying the index of the edit, and d, which is never changed in any case, is all there is. Targets are nodes of d; edits that build on nodes an earlier edit made go through an Editor. With no net change the new document is d itself.
Example ¶
Apply makes a list of edits atomically and returns a new snapshot; the document it started from is unchanged.
package main
import (
"fmt"
"recursiveai.org/go/onehtml"
)
func main() {
doc, _ := onehtml.ParseBytes([]byte(`<p id=a class=x>Hi</p>`))
p := doc.Body().FirstChild()
next, changes, err := doc.Apply(
onehtml.SetAttribute(p, "class", "y"),
onehtml.AppendHTML(p, "<b>there</b>"),
)
if err != nil {
panic(err)
}
fmt.Println(doc.Body().InnerHTML())
fmt.Println(next.Body().InnerHTML())
for c := range changes.With(onehtml.ChangeAttributes | onehtml.ChangeAdded) {
fmt.Println(c.Node.Name(), c.Kind&onehtml.ChangeAttributes != 0, c.Kind&onehtml.ChangeAdded != 0)
}
}
Output: <p id="a" class="x">Hi</p> <p id="a" class="y">Hi<b>there</b></p> p true false b false true
func (*Document) Body ¶
Body returns the body element of a document (a frameset also counts), or the zero Node.
func (*Document) DocumentElement ¶
DocumentElement returns the html element child of the document root.
func (*Document) Edit ¶
func (d *Document) Edit(opts ...EditorOption) *Editor
Edit returns an Editor that starts from d. For a nil or zero Document the editor has nothing to edit: every edit through it is refused.
Options set the editor's limits; see WithEditorLimits.
func (*Document) ElementByID ¶
ElementByID returns the first element in tree order whose id attribute is exactly id (case-sensitive), or the zero Node. An empty id matches nothing. Template contents are not searched.
Example ¶
package main
import (
"fmt"
"strings"
"recursiveai.org/go/onehtml"
)
func parseBody(s string) *onehtml.Document {
doc, err := onehtml.Parse(strings.NewReader(s))
if err != nil {
panic(err)
}
return doc
}
func main() {
doc := parseBody(`<p id=a>1</p><p id=b>2</p><template><p id=c></p></template>`)
fmt.Println(doc.ElementByID("b").TextContent(), doc.ElementByID("c").Valid())
}
Output: 2 false
func (*Document) Encoding ¶
Encoding returns the standard name of the encoding the bytes were decoded with, for example "UTF-8" or "windows-1252".
func (*Document) ErrorCount ¶
ErrorCount returns the number of parse errors found, including those past the limit that were not kept.
func (*Document) Errors ¶
func (d *Document) Errors() []ParseError
Errors returns the parse errors recorded, in input order, up to the Limits.MaxErrors limit.
Example ¶
Parse errors are recorded, never returned.
package main
import (
"fmt"
"recursiveai.org/go/onehtml"
)
func main() {
doc, _ := onehtml.ParseBytes([]byte("<p>a</i>"))
for _, e := range doc.Errors() {
fmt.Println(e.Code, e.Offset)
}
}
Output: unexpected-token 0 unexpected-end-tag 4
func (*Document) Generation ¶
Generation returns the number of commits behind this snapshot: 0 for a parsed document.
func (*Document) IsFragment ¶
IsFragment reports whether the document came from fragment parsing.
func (*Document) NodeAt ¶
NodeAt returns the node with the given Node.Index in d, or the zero Node when there is none. It finds a node again in a later snapshot, since a surviving node keeps its index across commits.
func (*Document) Nodes ¶
Nodes iterates over every node under the root (not template contents), in document order.
func (*Document) QuirksMode ¶
func (d *Document) QuirksMode() QuirksMode
QuirksMode returns the compatibility mode the doctype selected.
func (*Document) Root ¶
Root returns the document node, or for a fragment the fragment root. It is the zero Node for a nil or zero Document.
func (*Document) Select ¶
func (d *Document) Select(sel string, opts ...QueryOption) ([]Node, error)
Select returns the elements of the document that match the selector text, in document order. :scope is the document element.
Example ¶
The happy path: select with a selector string.
package main
import (
"fmt"
"strings"
"recursiveai.org/go/onehtml"
)
const exampleHTML = `<ul id=menu><li class=on><a href=/a>A</a><li><a href=/b>B</a><li class=on><a>C</a></ul>`
func main() {
doc, _ := onehtml.Parse(strings.NewReader(exampleHTML))
links, err := doc.Select("li.on > a[href]")
if err != nil {
panic(err)
}
for _, a := range links {
href, _ := a.Get("href")
fmt.Println(a.TextContent(), href)
}
}
Output: A /a
func (*Document) SelectFirst ¶
func (d *Document) SelectFirst(sel string, opts ...QueryOption) (Node, error)
SelectFirst returns the first element of the document that matches the selector text, or the zero Node.
func (*Document) SourceOffset ¶
SourceOffset maps an offset in Document.Text to an offset in Document.Source.
func (*Document) Style ¶
func (d *Document) Style(opts ...StyleOption) *Styles
Style builds the cascade for the document: the HTML standard's default style sheet, the document's <style> elements, linked sheets the caller supplies, @import from them, and the style attributes, under the context WithStyleContext gives (by default a 1280 x 720 light-scheme screen with no interaction state). Nothing is computed until an element is asked for. Sheets the caller does not supply are reported by Styles.Diagnostics and otherwise ignored. On a nil or zero Document it returns the styles of an empty document.
Example ¶
The happy path: style the document and read computed values, as getComputedStyle gives them.
package main
import (
"fmt"
"strings"
"recursiveai.org/go/onehtml"
)
const exampleStyled = `<!DOCTYPE html>
<style>
body { color: #333; font-size: 20px }
h1 { color: navy }
.note { color: gray; margin-left: 2em }
@media (min-width: 800px) { .note { color: black } }
</style>
<h1 id=title>Title</h1><p class=note id=n style="padding-top: 1em">A note</p>`
func main() {
doc, _ := onehtml.Parse(strings.NewReader(exampleStyled))
styles := doc.Style()
title, _ := doc.SelectFirst("#title")
note, _ := doc.SelectFirst("#n")
fmt.Println(styles.ComputedStyle(title).Get("color"), styles.ComputedStyle(title).Get("font-weight"))
fmt.Println(styles.ComputedStyle(note).Get("margin-left"), styles.ComputedStyle(note).Get("padding-top"))
}
Output: rgb(0, 0, 128) 700 40px 20px
func (*Document) Stylesheets ¶
func (d *Document) Stylesheets() []*Stylesheet
Stylesheets returns the <style> elements of the document as stylesheets named "inline:0", "inline:1", … in tree order. Elements of other namespaces and the contents of template elements are left out, as are style elements the parser made up (they have no source text).
func (*Document) Text ¶
Text returns the input decoded to UTF-8, which is where the parser read its text from. It equals Document.Source for UTF-8 input without a byte order mark or invalid sequences. The caller must not modify it.
type DocumentPosition ¶
type DocumentPosition uint8
DocumentPosition is the bit set Node.ComparePosition returns, with the DOM Standard's values for the bits of compareDocumentPosition.
const ( // PositionDisconnected: the nodes are in different trees. PositionDisconnected DocumentPosition = 1 << iota // PositionPreceding: the other node comes before this one in tree order. PositionPreceding // PositionFollowing: the other node comes after this one. PositionFollowing // PositionContains: the other node is an ancestor of this one. PositionContains // PositionContainedBy: the other node is a descendant of this one. PositionContainedBy // PositionImplementationSpecific: the order is arbitrary but consistent, // set with PositionDisconnected. PositionImplementationSpecific )
The bits of a DocumentPosition.
func (DocumentPosition) Has ¶
func (p DocumentPosition) Has(q DocumentPosition) bool
Has reports whether every bit of q is set in p.
func (DocumentPosition) String ¶
func (p DocumentPosition) String() string
String lists the set bits by name, comma separated, in bit order ("preceding,contains"); it is "" for no bits.
type DocumentRef ¶
type DocumentRef struct {
// URL is where the document came from, when known.
URL string
// SHA256 is the hex SHA-256 of the document's bytes, when it had any.
SHA256 string
}
DocumentRef records the document an envelope's edits were made against.
type Edit ¶
type Edit struct {
// contains filtered or unexported fields
}
Edit is one operation on one node of a snapshot, made with one of the constructors below and applied, with others, by Document.Apply. The operations are those of the family's edit list: edits of the tree and of style attributes (SetStyle, RemoveStyle) apply through Document.Apply, an Editor or Rewrite; edits of stylesheet rules and declarations (SetDeclaration, InsertRuleAfter, RemoveRule and the like) change a stylesheet's text, which has no tree, so only Rewrite makes them and Document.Apply refuses them with an *EditError. The zero Edit does nothing and is refused.
func AppendHTML ¶
AppendHTML inserts parsed markup as the last children of an element; see Editor.AppendHTML.
func AppendRule ¶
func AppendRule(s *Stylesheet, css string) Edit
AppendRule inserts the rule css at the end of the stylesheet.
func InsertHTMLAfter ¶
InsertHTMLAfter inserts parsed markup after n; see Editor.InsertHTMLAfter.
func InsertHTMLBefore ¶
InsertHTMLBefore inserts parsed markup before n; see Editor.InsertHTMLBefore.
func InsertRuleAfter ¶
InsertRuleAfter inserts the rule css (exactly one rule) after r.
func InsertRuleAtEndOf ¶
InsertRuleAtEndOf inserts the rule css as the last item of r's block.
func InsertRuleBefore ¶
InsertRuleBefore inserts the rule css (exactly one rule) before r.
func PrependHTML ¶
PrependHTML inserts parsed markup as the first children of an element; see Editor.PrependHTML.
func RemoveAttribute ¶
RemoveAttribute removes an attribute of an element; see Editor.RemoveAttribute.
func RemoveDeclaration ¶
RemoveDeclaration removes every declaration of the property from the rule; it changes nothing when there is none.
func RemoveNode ¶
RemoveNode removes n from the tree; see Editor.Remove.
func RemoveRule ¶
RemoveRule removes r and the white space that separated it from its neighbour.
func RemoveStyle ¶
RemoveStyle removes every declaration of the property from the style attribute of an element; it changes nothing when there is none.
func ReplaceRule ¶
ReplaceRule replaces r with the rule css (exactly one rule).
func ReplaceText ¶
ReplaceText replaces the data of a text or comment node, or all the children of an element with one text node; see Editor.ReplaceText.
func ReplaceWithHTML ¶
ReplaceWithHTML replaces n with parsed markup; see Editor.ReplaceWithHTML.
func SetAttribute ¶
SetAttribute sets an attribute of an element; see Editor.SetAttribute.
func SetDeclaration ¶
SetDeclaration replaces the value of the rule's last declaration of the property, or appends a declaration; !important is kept only when important is true. Property names compare ASCII case-insensitively except custom properties.
func SetStyle ¶
SetStyle sets a property in the style attribute of an element, editing only that declaration: it replaces the value of the last declaration of the property or appends one. !important is kept only when important is true.
Example ¶
SetStyle edits an element's style attribute declaration by declaration.
package main
import (
"fmt"
"recursiveai.org/go/onehtml"
)
func main() {
doc, _ := onehtml.ParseBytes([]byte(`<p style="color:red; margin:0">x</p>`))
p, _ := doc.SelectFirst("p")
res := onehtml.Rewrite(doc, []onehtml.Edit{
onehtml.SetStyle(p, "color", "blue", false),
onehtml.RemoveStyle(p, "margin"),
})
fmt.Println(string(res.Document))
}
Output: <p style="color:blue;">x</p>
func SetStyleKeepImportant ¶
SetStyleKeepImportant is SetStyle for a declaration whose importance is not being decided: an existing declaration keeps its !important or lack of it, and a new one is not important. It is what a saved setStyle edit with no "important" member does.
func Unwrap ¶
Unwrap replaces an element with its children; see Editor.Unwrap.
func WrapHTML ¶
WrapHTML wraps count siblings from n in the one element html describes; see Editor.WrapHTML.
func (Edit) WithMeta ¶
func (x Edit) WithMeta(meta json.RawMessage) Edit
WithMeta returns the edit carrying an opaque meta value, valid JSON that the library stores and never reads: NewEditFile writes it as the saved edit's "meta" member, compact, and ReplayDetail.Meta returns it. JSON that does not parse, and null, leave the edit without meta.
type EditError ¶
type EditError struct {
// Kind classifies the refusal; see [EditKind].
Kind EditKind
// Index is the position of the edit in the list given to
// [Document.Apply], or -1 for an edit made through an [Editor].
Index int
// Op names the operation, for example "setAttribute".
Op string
// Reason says why the edit was refused.
Reason string
// Err is the underlying error when there is one, such as a
// [*LimitError].
Err error
}
EditError reports an edit that cannot be made: a node of another document, a target of the wrong kind, a hierarchy the DOM forbids, an invalid name, or markup that does not fit the target. The document is unchanged.
type EditFile ¶
type EditFile struct {
// Document describes what the edits were made against. It is
// informative; replay does not use it.
Document *DocumentRef
// Edits are applied in order, all or none.
Edits []SavedEdit
}
EditFile is a decoded edit envelope: the saved edits of one transaction.
func NewEditFile ¶
NewEditFile turns in-memory edits of d and of its stylesheets into the saved form: an envelope whose targets are durable, so the edits can be replayed on another copy of the page. Every element target gets a locator, a fingerprint and, when it has source text, an anchor; a text or comment target gets its parent's target, its index among the parent's child nodes and a text fingerprint; a rule target names its sheet, selector, enclosing rules, index and declarations hash. The envelope's document member holds the SHA-256 of d's original bytes; set Document.URL on the result to record where the page came from.
The edits must be the kind Rewrite takes, aimed at nodes of d and rules of its stylesheets or of linked sheets that have a name (WithSheetName). An edit that cannot be saved (the zero Edit, a target from another document, an element with no locator, a linked sheet without a name) is refused with an *EditError carrying its index. Nothing is applied: the edits are not checked against the document beyond finding their targets.
Example ¶
NewEditFile saves in-memory edits as an envelope whose targets are durable; Replay finds them again, here in a copy that has changed, and says how.
package main
import (
"fmt"
"recursiveai.org/go/onehtml"
)
func main() {
page := `<div id="a">Hello</div><p>Para</p>`
doc, _ := onehtml.ParseBytes([]byte(page))
div := doc.Body().FirstChild()
file, err := onehtml.NewEditFile(doc, []onehtml.Edit{
onehtml.SetAttribute(div, "title", "t").WithMeta([]byte(`{"why": "demo"}`)),
})
if err != nil {
panic(err)
}
fmt.Println(file.Edits[0].Target.Locator)
// The same page with a paragraph added in front: the anchor no longer
// holds, the locator and fingerprint still name the one element.
later, _ := onehtml.ParseBytes([]byte(`<h1>New</h1>` + page))
res := onehtml.Replay(later, file)
fmt.Println(res.Outcomes, string(res.Document))
d := res.Details[0]
fmt.Println(d.UsedAnchor, d.PathMatched, d.Node.Name(), string(d.Meta))
}
Output: #a [applied] <h1>New</h1><div id="a" title="t">Hello</div><p>Para</p> false false div {"why":"demo"}
func ReadEditFile ¶
func ReadEditFile(data []byte, opts ...EditFileOption) (*EditFile, error)
ReadEditFile reads an edit envelope. Unknown members are ignored at every level, duplicate members keep the last value, a UTF-8 byte order mark is skipped, and text after the top-level value is an error, as are an edit that is not an object, a "format" other than "onehtml-edits" and a "version" other than the number 1. An edit with no "op" is accepted here; replay reports it invalid. limits bound the input before anything is built; the zero value selects the defaults.
Example ¶
A saved edit that finds its target applies; the envelope is written back as it was read.
package main
import (
"fmt"
"recursiveai.org/go/onehtml"
)
func main() {
file, _ := onehtml.ReadEditFile([]byte(`{"format":"onehtml-edits","version":1,"edits":[{"op":"unwrap","target":{"locator":"b","fingerprint":{"tag":"b"}}}]}`))
doc, _ := onehtml.ParseBytes([]byte(`<p><b>bold</b> text</p>`))
res := onehtml.Replay(doc, file)
fmt.Println(res.Outcomes[0], string(res.Document))
_, err := onehtml.ReadEditFile([]byte(`{"format":"onehtml-edits","version":2}`))
fmt.Println(err)
}
Output: applied <p>bold text</p> onehtml: edit file: "version" must be the number 1
type EditFileOption ¶
type EditFileOption func(*editFileConfig)
EditFileOption configures ReadEditFile.
func WithEditLimits ¶
func WithEditLimits(l EditLimits) EditFileOption
WithEditLimits replaces the default limits of ReadEditFile.
type EditKind ¶
type EditKind uint8
EditKind classifies why an *EditError refused an edit, using the DOM's error names.
const ( // EditKindOther is any other refusal: a target of the wrong kind, a // namespace that does not fit a name, a node or editor that is not usable. EditKindOther EditKind = iota // EditKindHierarchy is a placement the DOM's tree rules forbid: a node into // itself or its descendant, text under a document, a second document // element, a child under a node that cannot have children. EditKindHierarchy // EditKindNotFound is a reference node, or a node to remove or replace, that // is not a child of the parent given. EditKindNotFound // EditKindInvalidCharacter is a name that is not an XML Name, or a class // token that is empty or holds white space. EditKindInvalidCharacter // EditKindWrongDocument is a node of another document or of a snapshot the // editor no longer works on. EditKindWrongDocument // EditKindLimit is an edit that would exceed one of the editor's limits; the // error's Err is a [*LimitError]. EditKindLimit )
The kinds of refused edit.
type EditLimits ¶
type EditLimits struct {
// MaxBytes is the largest envelope in bytes. Default 32 MiB.
MaxBytes int
// MaxDepth is the deepest JSON nesting. Default 32.
MaxDepth int
// MaxEdits is the most edits in one envelope. Default 100,000.
MaxEdits int
// MaxString is the longest string in bytes. Default 16 MiB.
MaxString int
// MaxMeta is the most bytes of meta per edit; the total for the
// envelope may be 256 times as much. Default 64 KiB.
MaxMeta int
// MaxAttrs is the most attributes in one fingerprint. Default 64.
MaxAttrs int
// MaxAtRules is the most entries in one target's atRules. Default 64.
MaxAtRules int
}
EditLimits bound what ReadEditFile accepts. A zero field selects the default; a negative field removes the limit.
type EditOutcome ¶
type EditOutcome string
EditOutcome is what happened to one edit of a transaction.
const ( // EditApplied: the edit was made. EditApplied EditOutcome = "applied" // EditStale: a saved target is gone or no longer looks like it did. EditStale EditOutcome = "stale" // EditAmbiguous: a saved target matches several places. EditAmbiguous EditOutcome = "ambiguous" // EditInvalid: the operation does not fit the target, the operation is // unknown, or a member it needs is missing. EditInvalid EditOutcome = "invalid" // EditFailed: the result cannot be written losslessly. EditFailed EditOutcome = "failed" // EditNotAttempted: this edit was fine, but another edit was not, so // nothing was applied. EditNotAttempted EditOutcome = "notAttempted" )
The outcomes of an edit. A transaction applies all of its edits or none: unless every outcome is EditApplied, nothing was written.
type EditedRange ¶
type EditedRange struct {
Old Span
New []byte
// Edits are the indexes of the edits that produced the range.
Edits []int
// Level is 0 for a splice of exactly what changed, and n > 0 when the
// range was widened to the n-th enclosing element and rewritten from the
// expected tree (bytes inside it are not preserved).
Level int
}
EditedRange records one rewritten region of the document: replace Old of the original bytes with New and the output follows. It is the audit diff.
type Editor ¶
type Editor struct {
// contains filtered or unexported fields
}
Editor makes edits to a document and commits them as new snapshots. It is the mutating face of the snapshot model: the document it was made from is never changed, and each Editor.Commit produces a new Document that shares the text, source map and attribute storage of the old one and has a copy of the node records (a single memory copy).
Every method validates before it changes anything and returns an *EditError (or a *LimitError) when it refuses; a refused call leaves the pending edits as they were. Nodes passed in must belong to the editor's current document (the one it started from, or the latest commit) or be nodes the editor created; nodes of other snapshots are refused, and Document.NodeAt finds the same node in the current one. Reads of the pending state through a Node obtained from Editor.Pending see the edits made so far.
Make one with Document.Edit; the zero Editor and a nil *Editor have no document and refuse every edit. An Editor is for one goroutine at a time. The documents it commits are safe for concurrent reads.
Example ¶
An Editor builds up edits, node by node or from markup, and commits them as one snapshot. The change set says what a cascade or an accessibility tree has to refresh.
package main
import (
"fmt"
"strings"
"recursiveai.org/go/onehtml"
)
func main() {
doc, _ := onehtml.ParseBytes([]byte(`<ul><li>one</li></ul>`))
ed := doc.Edit()
li, _ := ed.CreateElement("li", onehtml.HTML)
txt, _ := ed.CreateText("two")
_ = ed.AppendChild(li, txt)
_ = ed.SetAttribute(li, "class", "new")
_ = ed.AppendChild(doc.Body().FirstChild(), li)
changes := ed.Commit()
fmt.Println(ed.Document().Body().InnerHTML())
for _, c := range changes.Changes {
var kinds []string
if c.Has(onehtml.ChangeChildren) {
kinds = append(kinds, "children")
}
if c.Has(onehtml.ChangeAdded) {
kinds = append(kinds, "added")
}
fmt.Println(c.Node.Name(), strings.Join(kinds, ","))
}
// Surviving nodes keep their index across snapshots.
ul := ed.Document().NodeAt(doc.Body().FirstChild().Index())
fmt.Println(ul.Name(), ul.Document() == ed.Document())
}
Output: <ul><li>one</li><li class="new">two</li></ul> ul children li added ul true
func (*Editor) AddClass ¶
AddClass adds class tokens to an element's class attribute, in order, skipping tokens it has, as the DOM's classList.add does. The attribute is rewritten, single-spaced, only when a token was added; with no tokens nothing happens. A token that is empty or holds ASCII white space refuses the whole call with an EditKindInvalidCharacter error.
func (*Editor) AppendChild ¶
AppendChild makes child the last child of parent, moving it from its current place if it has one. For a template element the parent is its contents. The DOM's rules apply: text under a document, a second document element, or inserting a node into itself is refused with an EditKindHierarchy error. A fragment node gives its children and is left empty.
Example ¶
A fragment holds nodes until it is inserted; inserting it moves its children and leaves it empty. A refusal says why, in the DOM's terms.
package main
import (
"errors"
"fmt"
"recursiveai.org/go/onehtml"
)
func main() {
doc, _ := onehtml.ParseBytes([]byte(`<ul id=u><li>one</li></ul>`))
ed := doc.Edit()
ul := doc.Body().FirstChild()
frag, _ := ed.CreateFragment()
for _, name := range []string{"li", "li"} {
li, _ := ed.CreateElement(name, onehtml.HTML)
_ = ed.AppendChild(frag, li)
}
if err := ed.AppendChild(ul, frag); err != nil {
panic(err)
}
fmt.Println(ed.Pending().Body().InnerHTML())
// A node cannot go into its own descendant.
err := ed.AppendChild(ul.FirstChild(), ul)
var ee *onehtml.EditError
fmt.Println(errors.As(err, &ee), ee.Kind)
}
Output: <ul id="u"><li>one</li><li></li><li></li></ul> true hierarchy-request
func (*Editor) AppendHTML ¶
AppendHTML parses html in the context of the element and inserts the nodes as its last children (those of the contents, for a template).
func (*Editor) Clone ¶
Clone copies n, or n and everything below it when deep is true, as detached nodes of the editor's document and returns the copy. n must belong to the editor, pending edits included. The copy has no source text; a template's contents are copied only when deep is true. Documents cannot be cloned. Editor.Import is the same for nodes of other documents.
func (*Editor) Commit ¶
Commit publishes the pending edits as a new snapshot and describes them. The snapshot is Editor.Document afterwards, and the editor goes on from it. With no net change and no node made it returns an empty set whose Old and New are the same document, and publishes nothing. Nodes made and left detached are published (the set is then empty with a New of its own), so that their handles stay usable.
func (*Editor) CreateComment ¶
CreateComment makes a detached comment node.
func (*Editor) CreateElement ¶
CreateElement makes a detached element. For HTML the name is folded to ASCII lower case; for SVG and MathML it is used as given. The name must look like an XML name (a letter, underscore, colon or non-ASCII character, then those or digits, hyphen or period). A template element comes with an empty contents fragment.
func (*Editor) CreateFragment ¶
CreateFragment makes an empty detached document fragment. Inserting it with Editor.AppendChild and the like inserts its children and leaves it empty.
func (*Editor) CreateText ¶
CreateText makes a detached text node. Invalid UTF-8 is replaced by U+FFFD.
func (*Editor) Document ¶
Document returns the latest committed snapshot: the document the editor started from until the first Editor.Commit. It is nil for an editor that has none.
func (*Editor) HasPending ¶
HasPending reports whether edits have been made since the last commit.
func (*Editor) Import ¶
Import copies n, or n and everything below it when deep is true, into the editor's document as detached nodes, and returns the copy. n may belong to any document. The copy has no source text. A template's contents are copied only when deep is true. Doctypes can be imported from the editor's own document only.
func (*Editor) InsertBefore ¶
InsertBefore places child under parent before ref, moving child from its current place if it has one. A zero ref appends. A ref that is not a child of parent is an EditKindNotFound error; see Editor.AppendChild for the rest.
func (*Editor) InsertHTMLAfter ¶
InsertHTMLAfter parses html in the context of n's parent and inserts the nodes after n.
func (*Editor) InsertHTMLBefore ¶
InsertHTMLBefore parses html in the context of n's parent and inserts the nodes before n. Markup that parses to nothing is not an edit.
func (*Editor) ParseFragment ¶
ParseFragment parses html with the fragment parsing algorithm in the context of the element ctx and returns a detached fragment node holding the result, ready to insert. Markup that parses to nothing gives an empty fragment.
func (*Editor) Pending ¶
Pending returns the document with the pending edits applied. It is the snapshot the next commit publishes; do not read it while editing from another goroutine, and do not keep reading it after further edits. Without pending edits it is Editor.Document.
func (*Editor) PrependChild ¶
PrependChild makes child the first child of parent; see Editor.AppendChild.
func (*Editor) PrependHTML ¶
PrependHTML parses html in the context of the element and inserts the nodes as its first children (those of the contents, for a template).
func (*Editor) Remove ¶
Remove detaches n, with everything below it, from its parent. The nodes stay readable through handles of the snapshots they were in. A document or fragment root cannot be removed.
func (*Editor) RemoveAttribute ¶
RemoveAttribute removes the attribute name from an element, matching as Editor.SetAttribute does. Removing an attribute the element lacks is not an edit.
func (*Editor) RemoveChild ¶
RemoveChild removes child from parent. A child that is not a child of parent is an EditKindNotFound error. For a template the parent is its contents.
func (*Editor) RemoveClass ¶
RemoveClass removes class tokens from an element's class attribute, as the DOM's classList.remove does. The attribute is rewritten, single-spaced, only when a token was removed; it stays, possibly empty, when the last one goes. Invalid tokens are refused as for Editor.AddClass.
func (*Editor) RemoveStyle ¶
RemoveStyle removes every declaration of the property from the element's style attribute; see the package-level RemoveStyle.
func (*Editor) ReplaceChild ¶
ReplaceChild puts child in the place of old, a child of parent, and returns with old detached. A fragment gives its children. An old that is not a child of parent is an EditKindNotFound error; see Editor.AppendChild for the rest. Nothing changes when it is refused.
func (*Editor) ReplaceChildren ¶
ReplaceChildren replaces all the children of parent (those of the contents, for a template) with nodes, in order; fragments give their children. It is all or nothing: when any node cannot be placed, nothing changes. A node that is a child of parent now is moved, a node listed twice is placed once, at its last position. A document is refused with EditKindHierarchy.
Example ¶
ReplaceChildren swaps all the children in one step, or changes nothing.
package main
import (
"fmt"
"recursiveai.org/go/onehtml"
)
func main() {
doc, _ := onehtml.ParseBytes([]byte(`<div><p>a</p><p>b</p></div>`))
ed := doc.Edit()
div := doc.Body().FirstChild()
text, _ := ed.CreateText("new")
fmt.Println(ed.ReplaceChildren(div, text))
fmt.Println(ed.Pending().Body().InnerHTML())
// The document element is an ancestor of div: refused, nothing moves.
err := ed.ReplaceChildren(div, doc.DocumentElement())
fmt.Println(err != nil, ed.Pending().Body().InnerHTML())
}
Output: <nil> <div>new</div> true <div>new</div>
func (*Editor) ReplaceText ¶
ReplaceText sets the character data of a text or comment node. For an element (a template's contents, for a template) it replaces all the children, elements and comments included, with one text node holding text, or with none when text is empty, as the DOM's textContent setter does. A text node keeps its place in the source; Node.Edited reports the change.
func (*Editor) ReplaceWithHTML ¶
ReplaceWithHTML parses html in the context of n's parent and puts the nodes in n's place; n is removed. Empty markup removes n.
func (*Editor) SetAttribute ¶
SetAttribute sets the attribute name of an element to value, replacing an existing attribute of that name in place (it keeps its position) or adding one at the end. On an HTML element the name is folded to ASCII lower case and matched without regard to case. On an SVG or MathML element "xlink:", "xml:" and "xmlns:" prefixes select the namespaces the parser gives those attributes. The name must look like an XML name, or the edit is refused with an EditKindInvalidCharacter error. Setting an attribute to the value it has is not an edit.
func (*Editor) SetAttributeNS ¶
SetAttributeNS sets the attribute with the qualified name qname in the namespace ns, which is NoNamespace, XLink, XML or XMLNS. The stored name is the part after the prefix. Names are not case-folded, and the DOM's namespace rules apply: a prefix needs a namespace, "xml" goes with XML, "xmlns" with XMLNS, and XMLNS with nothing else. A violation is an EditKindOther error, a name that is not an XML Name an EditKindInvalidCharacter one.
func (*Editor) SetInnerHTML ¶
SetInnerHTML replaces the children of an element (those of the contents, for a template) with the nodes html parses to in the element's context, as the DOM's innerHTML setter does. The old children are detached. Markup the parser limits refuse changes nothing.
Example ¶
SetInnerHTML parses markup in the element's context, as the DOM's innerHTML setter does; ParseFragment gives the nodes without placing them.
package main
import (
"fmt"
"recursiveai.org/go/onehtml"
)
func main() {
doc, _ := onehtml.ParseBytes([]byte(`<table><tr></tr></table><div>old</div>`))
ed := doc.Edit()
_ = ed.SetInnerHTML(doc.Body().LastChild(), `<b>new</b> text`)
tr := doc.Body().FirstChild().FirstChild().FirstChild()
cells, _ := ed.ParseFragment(`<td>1<td>2`, tr)
_ = ed.AppendChild(tr, cells)
fmt.Println(ed.Pending().Body().InnerHTML())
}
Output: <table><tbody><tr><td>1</td><td>2</td></tr></tbody></table><div><b>new</b> text</div>
func (*Editor) SetStyle ¶
SetStyle sets a property in the element's style attribute, editing only that declaration; see the package-level SetStyle.
func (*Editor) ToggleAttribute ¶
ToggleAttribute toggles the attribute name of an element as the DOM's toggleAttribute does: without force it removes the attribute when the element has it and adds it, empty, when it does not; with force it adds (true) or removes (false) it. It reports whether the element has the attribute afterwards. The name must look like an XML name, as for Editor.SetAttribute.
Example ¶
ToggleAttribute adds an empty attribute or removes it, or forces either.
package main
import (
"fmt"
"recursiveai.org/go/onehtml"
)
func main() {
doc, _ := onehtml.ParseBytes([]byte(`<input>`))
ed := doc.Edit()
in := doc.Body().FirstChild()
_, _ = ed.ToggleAttribute(in, "disabled")
fmt.Println(ed.Pending().Body().InnerHTML())
_, _ = ed.ToggleAttribute(in, "disabled", false)
_, _ = ed.ToggleAttribute(in, "hidden", false)
fmt.Println(ed.Pending().Body().InnerHTML())
}
Output: <input disabled=""> <input>
func (*Editor) ToggleClass ¶
ToggleClass toggles a class token as the DOM's classList.toggle does: without force it removes the token when present and adds it when not; with force it adds (true) or removes (false) it. It reports whether the element has the token afterwards. Invalid tokens are refused as for Editor.AddClass.
Example ¶
Class helpers follow the DOM's classList; the attribute is rewritten only when the set of tokens changes.
package main
import (
"fmt"
"recursiveai.org/go/onehtml"
)
func main() {
doc, _ := onehtml.ParseBytes([]byte(`<p class="a">x</p>`))
ed := doc.Edit()
p := doc.Body().FirstChild()
_ = ed.AddClass(p, "b", "c")
on, _ := ed.ToggleClass(p, "a")
_, _ = ed.ToggleClass(p, "d", true)
fmt.Println(on, ed.Pending().Body().InnerHTML())
}
Output: false <p class="b c d">x</p>
func (*Editor) Unwrap ¶
Unwrap replaces an element with its children (those of the contents, for a template), in order. The element is removed.
type EditorLimits ¶
type EditorLimits struct {
// MaxNodes is the most nodes the document may hold, detached ones and
// template contents included. Default 4 Mi.
MaxNodes int
// MaxAttributes is the most attributes one element may have. Default 4096.
MaxAttributes int
// MaxTotalAttributes is the most attributes the whole document may hold.
// Default: none.
MaxTotalAttributes int
// MaxDepth is the deepest nesting an edit may make. Default 1024.
MaxDepth int
// MaxValueLength is the longest attribute value or text node, in bytes.
// Default 1 GiB less one byte.
MaxValueLength int
// MaxNames is the most distinct names (beyond the standard ones) the
// document may hold. Default: none.
MaxNames int
}
EditorLimits bound what an Editor accepts. A zero field selects the default; a negative field removes the limit. A refused edit is an *EditError of kind EditKindLimit whose Err is a *LimitError.
type EditorOption ¶
type EditorOption func(*editorConfig)
EditorOption configures an Editor; see Document.Edit.
func WithEditorLimits ¶
func WithEditorLimits(l EditorLimits) EditorOption
WithEditorLimits sets the editor's limits. Fields left zero keep their defaults.
Example ¶
A limit refusal is an EditError of kind EditKindLimit that also matches ErrLimit.
package main
import (
"errors"
"fmt"
"recursiveai.org/go/onehtml"
)
func main() {
doc, _ := onehtml.ParseBytes([]byte(`<p>a</p>`))
ed := doc.Edit(onehtml.WithEditorLimits(onehtml.EditorLimits{MaxAttributes: 1}))
p := doc.Body().FirstChild()
fmt.Println(ed.SetAttribute(p, "a", "1"))
err := ed.SetAttribute(p, "b", "2")
fmt.Println(errors.Is(err, onehtml.ErrLimit), err)
}
Output: <nil> true onehtml: setAttribute: too many attributes: onehtml: attributes limit of 1 exceeded
type Fingerprint ¶
type Fingerprint struct {
Tag string
Attrs map[string]string
Text string
Path string
Declarations string
// PathText is the text Path hashes: "html[1]/body[2]/div[1]", each step
// the tag and its 1-based position among element siblings. It is set by
// [ElementFingerprint] and is not part of the saved form.
PathText string
// contains filtered or unexported fields
}
Fingerprint identifies what a target looked like when it was saved. For an element target Tag, Attrs, Text and Path are set; for a text or comment target only Text; for a rule target only Declarations. Hashes are written "sha256:" followed by lower-case hex.
func ElementFingerprint ¶
func ElementFingerprint(n Node) *Fingerprint
ElementFingerprint returns the fingerprint of an element: its tag, key attributes, the hash of its normalized text, and the hash of its position path (PathText holds the text that is hashed). It returns nil for a node that is not an element.
func (*Fingerprint) Compare ¶
func (f *Fingerprint) Compare(o *Fingerprint) FingerprintMatch
Compare compares two element fingerprints field by field, as Replay does when a locator selects an element: tag and attributes together, text, and path. A nil fingerprint matches nothing.
type FingerprintMatch ¶
type FingerprintMatch struct {
// TagAndAttributes reports that the tags are equal and the key
// attributes are the same set with equal values.
TagAndAttributes bool
// Text reports equal text hashes, and Path equal path hashes.
Text, Path bool
}
FingerprintMatch is the three-way comparison of two fingerprints.
type FocusSource ¶
type FocusSource uint8
FocusSource says how the focused element got focus, which decides :focus-visible.
const ( // FocusKeyboard is focus by keyboard (or any non-pointer means): the // element matches :focus-visible. FocusKeyboard FocusSource = iota // FocusPointer is focus by mouse, touch or pen: the element matches // :focus-visible only when it takes text input (a text field, a textarea // or an editing host), as browsers document it. FocusPointer )
Focus sources.
type FontMetrics ¶ added in v1.1.0
type FontMetrics struct {
// XHeight is the height of a lowercase x, which the ex and rex units are.
XHeight float64
// ZeroAdvance is the advance of the digit zero, which ch and rch are.
ZeroAdvance float64
// CapHeight is the height of a capital letter, which cap and rcap are.
CapHeight float64
// IdeographAdvance is the advance of a CJK water ideograph (U+6C34),
// which ic and ric are.
IdeographAdvance float64
}
FontMetrics are measurements of a font in units of its font size (em). A field that is zero is unknown and gets the estimate.
type FontMetricsFunc ¶ added in v1.1.0
type FontMetricsFunc func(FontQuery) FontMetrics
FontMetricsFunc measures the primary font of a FontQuery: the first family in the list that the caller has a face for. It is how the ex, ch, cap and ic units (and their root-relative forms) get real values, since the library has no fonts of its own. It may return the zero FontMetrics when it does not know the font. It is called while styles are computed, from any goroutine that reads them, and answers are kept per distinct query, so it must be safe for concurrent use and should be cheap.
type FontQuery ¶ added in v1.1.0
type FontQuery struct {
// Families is the computed font-family list in order: names without
// quotes, generic families by their keyword ("serif", "monospace").
Families []string
// Weight is the computed font-weight, 1 to 1000.
Weight float64
// Style is the computed font-style: "normal", "italic", "oblique" or
// "oblique" with an angle ("oblique 10deg").
Style string
// Stretch is the computed font-stretch as a percentage; 100 is normal.
Stretch float64
}
FontQuery names a font whose measurements are wanted: the computed font properties of the element the length is on (or of the root element, for the r-prefixed units).
type FormKind ¶
type FormKind uint8
FormKind names a piece of form state a document's markup gives an initial value to and a user can change.
const ( // FormChecked is the checkedness of a checkbox or radio button and the // selectedness of an option, what :checked reads. Making one radio button // of a group checked unchecks the others of its group; making one option // of a single-selection select selected deselects the others. FormChecked FormKind = iota // FormDisabled is whether a control is disabled, what :disabled and // :enabled read. On a fieldset it reaches the controls it contains. FormDisabled // FormIndeterminate is whether a checkbox, radio button or progress bar // is indeterminate, what :indeterminate reads. FormIndeterminate )
The form states.
type FormStates ¶
type FormStates struct {
// contains filtered or unexported fields
}
FormStates is a set of overrides of form state, as the user's changes to a form would be: a checkbox ticked, a control disabled, a checkbox set to indeterminate. The zero value overrides nothing, so the markup decides. A FormStates is immutable: its With… and Without methods return a new value and leave the receiver as it was, so one can be shared between queries and style contexts. Two FormStates are equal when they are the same value, not when they hold the same overrides.
Example ¶
A form the user has changed: tick a box and the style follows.
package main
import (
"fmt"
"strings"
"recursiveai.org/go/onehtml"
)
func main() {
doc, _ := onehtml.Parse(strings.NewReader(`<input id=a type=checkbox><input id=b type=checkbox checked>`))
a, _ := doc.SelectFirst("#a")
b, _ := doc.SelectFirst("#b")
fs := onehtml.FormStates{}.WithChecked(a, true).WithChecked(b, false)
checked, _ := doc.Select("input:checked", onehtml.WithFormStates(fs))
for _, n := range checked {
id, _ := n.Get("id")
fmt.Println(id)
}
}
Output: a
func (FormStates) Get ¶
func (f FormStates) Get(n Node, kind FormKind) (value, ok bool)
Get returns the override of kind on n and whether there is one.
func (FormStates) WithChecked ¶
func (f FormStates) WithChecked(n Node, v bool) FormStates
WithChecked returns the states with n's checkedness set to v.
func (FormStates) WithDisabled ¶
func (f FormStates) WithDisabled(n Node, v bool) FormStates
WithDisabled returns the states with n's disabledness set to v.
func (FormStates) WithIndeterminate ¶
func (f FormStates) WithIndeterminate(n Node, v bool) FormStates
WithIndeterminate returns the states with n's indeterminacy set to v.
func (FormStates) Without ¶
func (f FormStates) Without(n Node, kind FormKind) FormStates
Without returns the states with the override of kind on n removed, so the markup decides again.
type FormatError ¶
type FormatError struct {
// Message says what is wrong.
Message string
// Offset is the byte offset in the envelope where the problem was found,
// or -1 when it is not at one place (a missing member, a limit on a total).
Offset int
// contains filtered or unexported fields
}
FormatError reports an edit envelope the reader refuses: it is not JSON, has the wrong format or version, has trailing text, has an edit that is not an object, or exceeds a limit. It matches ErrEditFormat, and also ErrLimit when a limit of EditLimits was exceeded.
func (*FormatError) Is ¶
func (e *FormatError) Is(target error) bool
Is reports a match with ErrEditFormat, and with ErrLimit for a limit.
type FragmentContext ¶
type FragmentContext struct {
// Namespace of the context element: HTML, SVG or MathML.
Namespace Namespace
// Name is the context element's local name, for example "div" or "td".
Name string
// InsideForm says the context element is, or is inside, a form element:
// a form start tag in the fragment is then ignored, as the standard says
// for the form element pointer.
InsideForm bool
// IntegrationPoint says the context element, a MathML annotation-xml, is
// an HTML integration point (its encoding attribute is text/html or
// application/xhtml+xml). SVG foreignObject, desc and title are integration
// points by name and need no flag.
IntegrationPoint bool
// QuirksMode is the quirks mode of the context element's document; the
// zero value is [NoQuirks].
QuirksMode QuirksMode
}
FragmentContext is the context element of the fragment parsing algorithm: the element the markup is parsed as if it were the content of.
func FragmentContextOf ¶
func FragmentContextOf(n Node) FragmentContext
FragmentContextOf describes element n as the context of fragment parsing, with the things the standard derives from the element's surroundings: the namespace and name, whether n or an ancestor is a form, whether n is an HTML integration point (an annotation-xml with the matching encoding attribute), and the quirks mode of n's document. Use it to parse markup the way a browser does when setting innerHTML on n. A node that is not an element gives the zero context, an HTML body.
Example ¶
package main
import (
"fmt"
"strings"
"recursiveai.org/go/onehtml"
)
func main() {
page, _ := onehtml.Parse(strings.NewReader(`<form><div id="target"></div></form>`))
target, _ := page.SelectFirst("#target")
// Parse markup as if it were the content of the div, as setting innerHTML
// on it would: the context knows the div sits inside a form, so a nested
// <form> start tag is ignored.
ctx := onehtml.FragmentContextOf(target)
frag, _ := onehtml.ParseFragmentBytes([]byte(`<form><p>text`), ctx)
fmt.Println(ctx.InsideForm, frag.Root().FirstChild().Name())
}
Output: true p
type InteractionState ¶
type InteractionState uint8
InteractionState names the user-interaction pseudo-classes whose truth the document cannot know. A WithState function answers for them.
const ( StateHover InteractionState = iota StateActive StateFocus StateFocusVisible StateFocusWithin )
The interaction states.
type InternalError ¶
type InternalError struct {
// Value is the value the parser panicked with.
Value any
}
InternalError reports a bug in this package: the parser panicked. Input, however hostile, must never cause it; if you see one, please report the input that did.
func (*InternalError) Error ¶
func (e *InternalError) Error() string
Error describes the panic value.
type InvalidDeclaration ¶ added in v1.1.0
type InvalidDeclaration struct {
// Property is the property the declaration names: a shorthand by its own
// name, a custom property with its "--".
Property string
// Value is the declaration's value as written, trimmed.
Value string
// Source says where the declaration is.
Source Source
}
InvalidDeclaration is a declaration that won the cascade for an element but has no value for it, because it is invalid at computed-value time (CSS Custom Properties 1, section 3.1): a var() whose substituted value does not fit the property, a shorthand that does not expand once substituted, a custom property that refers to nothing, or one whose value does not fit its registered syntax. The property then behaves as if unset.
type KeyframeBlock ¶
type KeyframeBlock struct {
// Offset is the selector as a number from 0 to 1: "from" is 0 and "to" is 1.
Offset float64
// TimingFunction and Composition are the block's own animation-timing-function
// and animation-composition as written, or "" when it sets none.
TimingFunction, Composition string
// Declarations are the block's valid declarations that are not !important,
// in the order written, with shorthands split into longhands. The animation
// properties other than the two above have no effect in a block and are
// left out.
Declarations []KeyframeDeclaration
// contains filtered or unexported fields
}
KeyframeBlock is one keyframe selector of a rule and the declarations of its block.
type KeyframeDeclaration ¶
type KeyframeDeclaration struct {
// Property is the lower-case property name.
Property string
// Value is the specified text of the value with its white space trimmed.
Value string
// UsesVar is true when the value holds var(). A shorthand with var() is not
// split: its longhands are known only for an element.
UsesVar bool
}
KeyframeDeclaration is one declaration of a keyframe block.
type KeyframeValue ¶
type KeyframeValue struct {
Property string
// Value is the specified text of the value with var() substituted from the
// element's custom properties, or the element's computed value for the 0%
// and 100% keyframes that lack the property.
Value string
// Invalid is true when the substitution failed or the result is not valid for
// the property; Value is then "unset".
Invalid bool
}
KeyframeValue is the value of one property in a keyframe.
type KeyframesRule ¶
type KeyframesRule struct {
// Name is the keyframes name, unescaped; a string and an identifier that
// spell the same name are one name. Names are case-sensitive.
Name string
// Prefixed is true for an @-webkit-keyframes rule, the alias the
// Compatibility Standard defines.
Prefixed bool
// Blocks has one entry for each selector of each keyframe block, in the order
// written. A block whose selector list holds an invalid selector is not here.
Blocks []KeyframeBlock
// Origin is the origin of the style sheet that holds the rule.
Origin Origin
// Layer is the cascade layer the rule is in, as a dotted path, or "" for
// the unlayered rules.
Layer string
// contains filtered or unexported fields
}
KeyframesRule is the winning @keyframes rule of a name; see Styles.Keyframes.
type LimitError ¶
type LimitError struct {
// Limit names the limit: one of the Limit constants.
Limit string
// Max is the value that was exceeded.
Max int
}
LimitError reports that the input exceeded one of the Limits. No document is returned.
func (*LimitError) Error ¶
func (e *LimitError) Error() string
Error describes the limit that was exceeded.
type Limits ¶
type Limits struct {
// MaxInputBytes is the largest input read, in bytes. Default 64 MiB.
MaxInputBytes int
// MaxDepth is the deepest nesting of open elements, html and body
// included. Default 4096.
MaxDepth int
// MaxFormattingElements is the longest list of active formatting
// elements. Default 1024.
MaxFormattingElements int
// MaxAttributes is the most attributes one tag may have, duplicates
// counted. Default 4096; 65535 is the most any setting allows.
MaxAttributes int
// MaxTotalAttributes is the most attributes all elements of a document
// may have together, the copies made when active formatting elements
// are reconstructed included. Default 8,388,608.
MaxTotalAttributes int
// MaxOffsetRuns is the most runs the map from decoded text back to the
// input bytes may have. Input in UTF-8 needs one run however much
// non-ASCII text it holds; other encodings need a run for each
// character whose width changes in decoding. Default 16,777,216.
MaxOffsetRuns int
// MaxNodes is the most nodes a document may have, text and template
// contents included. Default 4,194,304.
MaxNodes int
// MaxErrors is the most parse errors recorded; later ones are counted in
// [Document.ErrorCount] but not kept. Default 1000.
MaxErrors int
}
Limits bound what the parser accepts from untrusted input. A zero field selects the default; a negative field removes that limit. A limit that is exceeded makes the parse fail with a *LimitError; the check comes before the work it guards, so a hostile input cannot make the parser allocate past it (the node limit can be overshot by at most the size of the list of active formatting elements, which the node limit itself bounds).
Example ¶
Limits fail the parse with an error that matches ErrLimit.
package main
import (
"errors"
"fmt"
"recursiveai.org/go/onehtml"
)
func main() {
_, err := onehtml.ParseBytes([]byte("<a><b><i>"), onehtml.WithLimits(onehtml.Limits{MaxDepth: 4}))
fmt.Println(errors.Is(err, onehtml.ErrLimit))
var le *onehtml.LimitError
if errors.As(err, &le) {
fmt.Println(le.Limit, le.Max)
}
}
Output: true depth 4
type LocatorIndex ¶
type LocatorIndex struct {
// contains filtered or unexported fields
}
A LocatorIndex generates locators for the elements of one document. Build it once with NewLocatorIndex; each call to LocatorIndex.Locator is then cheap. The index reads the document it was made for and keeps no state that changes, so it is safe for concurrent use once built. A nil *LocatorIndex finds no locators.
Example ¶
Saved edits name their targets by locator, fingerprint and anchor. A LocatorIndex makes the locator of an element that is unique in the document; MarshalEditFile writes the envelope, always with the same bytes for the same edits.
package main
import (
"fmt"
"strings"
"recursiveai.org/go/onehtml"
)
func main() {
doc, _ := onehtml.ParseBytes([]byte(`<ul><li id=a>one</li><li>two</li></ul>`))
ix := onehtml.NewLocatorIndex(doc)
second := doc.Body().FirstChild().LastChild()
loc, ok := ix.Locator(second)
fmt.Println(loc, ok)
target, _ := ix.Target(second)
edit := onehtml.SavedEdit{Op: "setAttribute", Target: target, Name: "class", Value: "last"}
edit.Set(onehtml.MemberName | onehtml.MemberValue)
file := &onehtml.EditFile{Edits: []onehtml.SavedEdit{edit}}
saved := onehtml.MarshalEditFile(file)
fmt.Println(strings.HasPrefix(string(saved), `{"format":"onehtml-edits","version":1,"edits":[{"op":"setAttribute"`))
// The envelope finds its target again on a copy of the page.
again, _ := onehtml.ReadEditFile(saved)
res := onehtml.Replay(doc, again)
fmt.Println(res.Outcomes[0], string(res.Document))
}
Output: ul > li:nth-of-type(2) true true applied <ul><li id=a>one</li><li class="last">two</li></ul>
func NewLocatorIndex ¶
func NewLocatorIndex(d *Document) *LocatorIndex
NewLocatorIndex counts the selector candidates of every element of the document, so that unique ones can be chosen.
func (*LocatorIndex) Locator ¶
func (ix *LocatorIndex) Locator(n Node) (string, bool)
Locator returns a selector that matches exactly n in its document: the first unique candidate of n or its nearest ancestor that has one, then the structural steps down from there. It reports false for nodes that are not elements of the document tree (template contents included) and for elements more than 120 steps below any anchor.
func (*LocatorIndex) Target ¶
func (ix *LocatorIndex) Target(n Node) (*Target, bool)
Target returns the durable target of a node: for an element its locator, fingerprint and, when it has source, its anchor; for a text or comment node its parent's target, index and text hash. It reports false when no locator exists.
func (*LocatorIndex) Verify ¶
func (ix *LocatorIndex) Verify(n Node, locator string) bool
Verify reports whether locator is a selector that matches exactly n among the elements of the document: one that does not parse, matches nothing, matches another element or matches several is false. It queries the whole document, so it costs a full pass; it is meant for tests and audits.
Example ¶
Locators name one element durably; Verify checks a selector names exactly one, and fingerprints compare what an element looked like.
package main
import (
"fmt"
"recursiveai.org/go/onehtml"
)
func main() {
doc, _ := onehtml.ParseBytes([]byte(`<div id="a"><p>x</p><p>y</p></div>`))
p := doc.Body().FirstChild().FirstChild()
ix := onehtml.NewLocatorIndex(doc)
loc, _ := ix.Locator(p)
fmt.Println(loc, ix.Verify(p, loc), ix.Verify(p, "p"))
m := onehtml.ElementFingerprint(p).Compare(onehtml.ElementFingerprint(p.NextSibling()))
fmt.Println(m.TagAndAttributes, m.Text, m.Path)
fmt.Println(onehtml.IsGeneratedName("css-1x2y3z"), onehtml.IsGeneratedName("nav-link"))
}
Output: #a > p:nth-of-type(1) true false true false false true false
type MarshalOption ¶
type MarshalOption func(*marshalConfig)
MarshalOption configures MarshalEditFile.
func WithEditFileIndent ¶
func WithEditFileIndent(on bool) MarshalOption
WithEditFileIndent writes the envelope indented, for people to read.
type MatchedRule ¶
type MatchedRule struct {
// Origin of the sheet the rule is in.
Origin Origin
// Sheet is the index in [Styles.Sheets] of the sheet the rule is in.
Sheet int
// Selector is the rule's selector list as written (for a nested rule, as
// written inside its parent).
Selector string
// Specificity is that of the selector of the list that matched.
Specificity Specificity
// Layer is the dotted name of the cascade layer the rule is in, empty when
// unlayered; a layer without a name shows as an empty part.
Layer string
// Nested is true for a rule nested in another, and for the declarations
// that follow a nested rule.
Nested bool
// Declarations are the rule's valid declarations in source order.
Declarations []MatchedStyleDeclaration
// Span is the byte range of the rule in its sheet's text.
Span Span
}
MatchedRule is a style rule that matched an element, with the part of the cascade it took part in.
type MatchedStyleDeclaration ¶
MatchedStyleDeclaration is one declaration of a MatchedRule.
type Matcher ¶
type Matcher struct {
// contains filtered or unexported fields
}
Matcher matches elements against compiled selectors. It caches work between calls, so reuse one Matcher for many elements of one document; a Matcher is not safe for concurrent use. The cascade drives it one complex selector at a time.
Example ¶
The cascade drives a Matcher: one complex selector at a time, with its specificity, and the pseudo-element it ends in.
package main
import (
"fmt"
"strings"
"recursiveai.org/go/onehtml"
)
const exampleHTML = `<ul id=menu><li class=on><a href=/a>A</a><li><a href=/b>B</a><li class=on><a>C</a></ul>`
func main() {
doc, _ := onehtml.Parse(strings.NewReader(exampleHTML))
sel := onehtml.MustCompileSelector("li.on::marker, li")
li, _ := doc.SelectFirst("li")
m := onehtml.NewMatcher()
for i := 0; i < sel.Len(); i++ {
fmt.Printf("%q matches=%v specificity=%v\n", sel.PseudoElement(i), m.MatchesItem(sel, i, li), sel.Specificity(i))
}
}
Output: "marker" matches=true specificity={0 1 2} "" matches=true specificity={0 0 1}
func NewMatcher ¶
func NewMatcher(opts ...QueryOption) *Matcher
NewMatcher returns a Matcher with the given options.
type Namespace ¶
type Namespace uint8
Namespace identifies an element's or attribute's namespace.
const ( // NoNamespace is the namespace of ordinary attributes. NoNamespace Namespace = iota // HTML is the HTML namespace. HTML // SVG is the SVG namespace. SVG // MathML is the MathML namespace. MathML // XLink is the namespace of xlink: attributes. XLink // XML is the namespace of xml: attributes. XML // XMLNS is the namespace of xmlns attributes. XMLNS )
Namespaces. The first three are element namespaces; the others occur on attributes the parser adjusts for foreign content.
func (Namespace) String ¶
String returns the short name: "html", "svg", "math", "xlink", "xml" or "xmlns", and "" for NoNamespace.
func (Namespace) URI ¶
URI returns the namespace's URI, or "" for NoNamespace.
type Node ¶
type Node struct {
// contains filtered or unexported fields
}
Node is a handle to a node of a Document. Handles are small values; compare them with ==. The zero Node is invalid and every method on it returns the zero value of its result.
func (Node) AnchorSpan ¶
AnchorSpan returns the source range the node's existence is attributed to. For a node written in the source it is the start tag of an element and the whole construct of any other node. An implied element has the empty range at the start of the token that made the parser insert it; a clone has the range of the start tag it copies. It is absent for a node with no such place (a selectedcontent copy, template contents, the document).
func (Node) AppendInnerHTML ¶
AppendInnerHTML appends the serialization Node.InnerHTML returns to dst.
func (Node) AppendOuterHTML ¶
AppendOuterHTML appends the serialization Node.OuterHTML returns to dst.
func (Node) Attribute ¶
Attribute returns the attribute with the given name and no namespace. For an HTML element the name is compared ASCII case-insensitively.
func (Node) AttributeNS ¶
AttributeNS returns the attribute with the given namespace and exact local name. Use NoNamespace for ordinary attributes; unlike Node.Attribute the name is not case-folded.
Example ¶
package main
import (
"fmt"
"strings"
"recursiveai.org/go/onehtml"
)
func parseBody(s string) *onehtml.Document {
doc, err := onehtml.Parse(strings.NewReader(s))
if err != nil {
panic(err)
}
return doc
}
func main() {
doc := parseBody(`<svg><use xlink:href="#a"></use></svg>`)
use := doc.Body().FirstChild().FirstChild()
a, _ := use.AttributeNS(onehtml.XLink, "href")
_, plain := use.AttributeNS(onehtml.NoNamespace, "href")
fmt.Println(a.QualifiedName(), a.Value(), plain)
}
Output: xlink:href #a false
func (Node) ChildElementCount ¶
ChildElementCount returns the number of element children of n.
func (Node) ChildElements ¶
ChildElements iterates over the element children of n in document order.
Example ¶
package main
import (
"fmt"
"strings"
"recursiveai.org/go/onehtml"
)
func parseBody(s string) *onehtml.Document {
doc, err := onehtml.Parse(strings.NewReader(s))
if err != nil {
panic(err)
}
return doc
}
func main() {
doc := parseBody(`<ul>a<li>1</li>b<li>2</li><!--c--></ul>`)
ul := doc.Body().FirstElementChild()
for li := range ul.ChildElements() {
fmt.Println(li.TextContent())
}
fmt.Println(ul.ChildElementCount(), ul.LastElementChild().PrevElementSibling().TextContent())
}
Output: 1 2 2 1
func (Node) Children ¶
Children iterates over the children in document order. A template element's children are those of its contents; see Node.TemplateContent.
func (Node) Classes ¶
Classes iterates over the distinct tokens of an element's class attribute in the order they first appear, as an ordered set the way the DOM's classList reads. Tokens are separated by ASCII whitespace; a no-break space belongs to the token. Case is kept.
func (Node) Closest ¶
func (n Node) Closest(sel string, opts ...QueryOption) (Node, error)
Closest returns n or its nearest ancestor element that the selector text matches, or the zero Node (Element.closest).
Example ¶
package main
import (
"fmt"
"strings"
"recursiveai.org/go/onehtml"
)
const exampleHTML = `<ul id=menu><li class=on><a href=/a>A</a><li><a href=/b>B</a><li class=on><a>C</a></ul>`
func main() {
doc, _ := onehtml.Parse(strings.NewReader(exampleHTML))
a, _ := doc.SelectFirst("a:not([href])")
li, _ := a.Closest("li")
menu, _ := a.Closest("ul#menu")
fmt.Println(li.Name(), li.Has("class"), menu.Name())
}
Output: li true ul
func (Node) ComparePosition ¶
func (n Node) ComparePosition(o Node) DocumentPosition
ComparePosition describes where o is relative to n, as the DOM's compareDocumentPosition does. It is 0 for the same node. Nodes of different trees, or of different documents, are disconnected and implementation-specific; within one document that order is consistent (o and n swap preceding and following). Nodes of different documents, and the zero Node, always compare as following.
Example ¶
package main
import (
"fmt"
"strings"
"recursiveai.org/go/onehtml"
)
func parseBody(s string) *onehtml.Document {
doc, err := onehtml.Parse(strings.NewReader(s))
if err != nil {
panic(err)
}
return doc
}
func main() {
doc := parseBody(`<div><p></p><i></i></div>`)
div := doc.Body().FirstChild()
p, i := div.FirstChild(), div.LastChild()
fmt.Println(p.ComparePosition(i), "|", i.ComparePosition(p), "|", p.ComparePosition(div), "|", div.ComparePosition(p))
fmt.Println(div.Contains(i), i.Contains(div), i.IsConnected(), i.RootNode() == doc.Root())
}
Output: following | preceding | preceding,contains | following,contained-by true false true true
func (Node) Contains ¶
Contains reports whether o is n or one of its descendants. Template contents are separate trees: a template does not contain its contents.
func (Node) Data ¶
Data returns the character data of a text or comment node, or the data of a processing instruction, and "" for other kinds.
func (Node) DataSpan ¶
DataSpan returns the byte range of a text, comment or processing instruction node's character data as written in the source, without the markup around it. It is absent when the data is not a verbatim slice of the source: a character reference was decoded, NUL replaced, or text from more than one place was joined. Line-break normalisation does not count; the range covers the break as written. It is absent for other kinds of node.
Example ¶
package main
import (
"fmt"
"recursiveai.org/go/onehtml"
)
func main() {
src := `<p>a&b</p><!-- note -->`
doc, _ := onehtml.ParseBytes([]byte(src))
text := doc.Body().FirstChild().FirstChild()
comment := doc.Body().FirstChild().NextSibling()
fmt.Println(text.DataSpan().Valid()) // a character reference was decoded
cs := comment.DataSpan()
fmt.Printf("%q\n", src[cs.Start:cs.End])
}
Output: false " note "
func (Node) DescendantElements ¶
DescendantElements iterates over the element descendants of n in document order. Like Node.Descendants it does not enter template contents.
func (Node) Descendants ¶
Descendants iterates over all descendants, depth first in document order, without recursion. It does not enter template contents.
func (Node) Doctype ¶
func (n Node) Doctype() (DoctypeInfo, bool)
Doctype returns the name and identifiers of a doctype node, and false for any other kind of node.
func (Node) Edited ¶
Edited reports whether an edit changed the node's own attributes or character data since the parse. Source ranges of an edited node still describe the original text; an edited element's attributes without a Attr.Span are the ones the edits wrote.
func (Node) ElementsByClassName ¶
ElementsByClassName iterates over the element descendants of n that have every token of names in their class attribute, in tree order. names is split at ASCII whitespace; with no tokens nothing matches. Case is folded in a quirks-mode document only.
Example ¶
package main
import (
"fmt"
"strings"
"recursiveai.org/go/onehtml"
)
func parseBody(s string) *onehtml.Document {
doc, err := onehtml.Parse(strings.NewReader(s))
if err != nil {
panic(err)
}
return doc
}
func main() {
doc := parseBody(`<p class="a b">1</p><p class=a>2</p><p class="b a c">3</p>`)
for p := range doc.Root().ElementsByClassName("a b") {
fmt.Print(p.TextContent(), " ")
}
fmt.Println()
}
Output: 1 3
func (Node) ElementsByTagName ¶
ElementsByTagName iterates over the element descendants of n (n itself excluded) with the given tag name, in tree order, as getElementsByTagName does: "*" matches every element; otherwise the name is folded to ASCII lower case for HTML elements and compared as given for SVG and MathML elements.
Example ¶
package main
import (
"fmt"
"strings"
"recursiveai.org/go/onehtml"
)
func parseBody(s string) *onehtml.Document {
doc, err := onehtml.Parse(strings.NewReader(s))
if err != nil {
panic(err)
}
return doc
}
func main() {
doc := parseBody(`<div><P>1</P><span><p>2</p></span></div>`)
for p := range doc.Body().ElementsByTagName("P") {
fmt.Print(p.TextContent(), " ")
}
fmt.Println()
}
Output: 1 2
func (Node) ElementsByTagNameNS ¶
ElementsByTagNameNS iterates over the element descendants of n with the given namespace URI and local name, as getElementsByTagNameNS does: "*" for either matches any. An unknown URI matches nothing. Names are compared exactly.
Example ¶
package main
import (
"fmt"
"strings"
"recursiveai.org/go/onehtml"
)
func parseBody(s string) *onehtml.Document {
doc, err := onehtml.Parse(strings.NewReader(s))
if err != nil {
panic(err)
}
return doc
}
func main() {
doc := parseBody(`<p></p><svg><circle></circle></svg>`)
for e := range doc.Root().ElementsByTagNameNS(onehtml.SVG.URI(), "*") {
fmt.Print(e.Name(), " ")
}
fmt.Println()
}
Output: svg circle
func (Node) EndTagSpan ¶
EndTagSpan returns the byte range of an element's end tag. It is absent when the element has none in the source (void elements, implied closes).
func (Node) FirstChild ¶
FirstChild returns the first child, or the zero Node.
func (Node) FirstElementChild ¶
FirstElementChild returns the first child that is an element, or the zero Node.
func (Node) HasClass ¶
HasClass reports whether the element's class attribute holds the token. Matching is case-sensitive, except in a document in quirks mode (not limited-quirks), where ASCII case is folded, as selectors and getElementsByClassName do there.
Example ¶
package main
import (
"fmt"
"strings"
"recursiveai.org/go/onehtml"
)
func parseBody(s string) *onehtml.Document {
doc, err := onehtml.Parse(strings.NewReader(s))
if err != nil {
panic(err)
}
return doc
}
func main() {
standards := parseBody(`<!DOCTYPE html><p class=Note>`)
quirks := parseBody(`<p class=Note>`)
fmt.Println(standards.Body().FirstChild().HasClass("note"), quirks.Body().FirstChild().HasClass("note"))
}
Output: false true
func (Node) ID ¶
ID returns the value of an element's id attribute, or "" when it has none or n is not an element.
func (Node) Index ¶
Index returns the node's position in its document's arena. Snapshots made by successive commits keep a surviving node's index and never reuse the index of a removed one, so it can key side tables across a chain of snapshots; it is not an index among siblings. It is -1 for the zero Node.
func (Node) InnerHTML ¶
InnerHTML returns the HTML serialization of the children of n (of the contents, for a template element). It is "" for a void element and for nodes that have no children.
func (Node) IsConnected ¶
IsConnected reports whether n is in a document that was parsed as a whole: its root is the document node. Nodes of a fragment, and template contents, are not connected.
func (Node) LastElementChild ¶
LastElementChild returns the last child that is an element, or the zero Node.
func (Node) Matches ¶
func (n Node) Matches(sel string, opts ...QueryOption) (bool, error)
Matches reports whether n is an element the selector text matches (Element.matches).
Example ¶
package main
import (
"fmt"
"strings"
"recursiveai.org/go/onehtml"
)
const exampleHTML = `<ul id=menu><li class=on><a href=/a>A</a><li><a href=/b>B</a><li class=on><a>C</a></ul>`
func main() {
doc, _ := onehtml.Parse(strings.NewReader(exampleHTML))
li, _ := doc.SelectFirst("li")
ok, _ := li.Matches(":is(.on, .off):has(> a[href])")
fmt.Println(ok)
}
Output: true
func (Node) Moved ¶
Moved reports whether an edit placed the node, which has source text, under a parent: its source range is where it was in the original input, not where it is in the tree. Nodes an edit created have no source and are not reported.
func (Node) Name ¶
Name returns an element's local name: lower-case for HTML elements, and as the standard's adjusted case for SVG and MathML ("foreignObject"). It is the empty string for other kinds of node.
func (Node) Namespace ¶
Namespace returns an element's namespace. It is NoNamespace for other kinds of node.
func (Node) NextElementSibling ¶
NextElementSibling returns the nearest following sibling that is an element, or the zero Node.
func (Node) NextSibling ¶
NextSibling returns the next sibling, or the zero Node.
func (Node) OuterHTML ¶
OuterHTML returns the HTML serialization of n itself and everything below it, by the standard's HTML fragment serialization algorithm. A document or fragment node has no tag of its own, so its outer and inner HTML agree. A template element's contents are serialized in place of its children.
func (Node) PITarget ¶
PITarget returns the target of a processing instruction, and "" for other kinds of node.
func (Node) PrevElementSibling ¶
PrevElementSibling returns the nearest preceding sibling that is an element, or the zero Node.
func (Node) PrevSibling ¶
PrevSibling returns the previous sibling, or the zero Node.
func (Node) Provenance ¶
func (n Node) Provenance() Provenance
Provenance returns how n came to exist other than being written plainly; it is 0 for such a node and for the zero Node. Node.Synthetic, Node.Reparented and Node.SelfClosing read single flags.
Example ¶
package main
import (
"fmt"
"strings"
"recursiveai.org/go/onehtml"
)
func parseBody(s string) *onehtml.Document {
doc, err := onehtml.Parse(strings.NewReader(s))
if err != nil {
panic(err)
}
return doc
}
func main() {
doc := parseBody(`<p>x</p><br/>`)
fmt.Printf("%q %q\n", doc.Head().Provenance(), doc.Body().LastChild().Provenance())
p := doc.Body().FirstChild()
fmt.Println(p.Provenance() == 0, p.AnchorSpan(), doc.Head().AnchorSpan())
}
Output: "implied-start-tag" "self-closing-syntax" true {0 3} {0 0}
func (Node) Reparented ¶
Reparented reports whether foster parenting or the adoption agency algorithm moved the node away from where the source puts it.
func (Node) RootNode ¶
RootNode returns the topmost ancestor of n, which is n itself for a node with no parent. The root of a template's contents is the contents fragment.
func (Node) Select ¶
func (n Node) Select(sel string, opts ...QueryOption) ([]Node, error)
Select returns the descendants of n that match the selector text, in document order (querySelectorAll). It is the happy path over CompileSelector and Selector.All; the error matches ErrSelectorSyntax or ErrSelectorLimit. To run one selector often, compile it once.
Example ¶
:scope is the element the query starts from.
package main
import (
"fmt"
"strings"
"recursiveai.org/go/onehtml"
)
const exampleHTML = `<ul id=menu><li class=on><a href=/a>A</a><li><a href=/b>B</a><li class=on><a>C</a></ul>`
func main() {
doc, _ := onehtml.Parse(strings.NewReader(exampleHTML))
menu, _ := doc.SelectFirst("#menu")
items, _ := menu.Select(":scope > li")
fmt.Println(len(items))
}
Output: 3
func (Node) SelectFirst ¶
func (n Node) SelectFirst(sel string, opts ...QueryOption) (Node, error)
SelectFirst returns the first descendant of n that matches the selector text, or the zero Node when none does (querySelector).
func (Node) SelfClosing ¶
SelfClosing reports whether an element's start tag ended with a solidus.
func (Node) Span ¶
Span returns the node's byte range in the original input: for an element, from the start tag to the end of the end tag (or to where parsing closed it). It is absent for nodes the parser made without source.
Example ¶
The low level: every node and attribute knows where it came from.
package main
import (
"fmt"
"recursiveai.org/go/onehtml"
)
func main() {
src := []byte(`<div id='a'><b>x</b></div>`)
doc, _ := onehtml.ParseBytes(src)
b := doc.Body().FirstChild().FirstChild()
sp := b.Span()
fmt.Printf("%s %q\n", b.Name(), src[sp.Start:sp.End])
id, _ := doc.Body().FirstChild().Attribute("id")
vs := id.ValueSpan()
fmt.Printf("%q quote=%c\n", src[vs.Start:vs.End], id.Quote())
}
Output: b "<b>x</b>" "a" quote='
func (Node) StartTagSpan ¶
StartTagSpan returns the byte range of an element's start tag.
func (Node) Synthetic ¶
Synthetic reports whether the parser created the node with no tag of its own in the source: an implied html, head, body or tbody, or an element recreated by the adoption agency algorithm.
func (Node) TagName ¶
TagName returns the element's tag name as the DOM's tagName reads it: the local name in ASCII upper case for an HTML element, and the name as stored for SVG and MathML elements. It is "" for other kinds of node.
Example ¶
package main
import (
"fmt"
"slices"
"strings"
"recursiveai.org/go/onehtml"
)
func parseBody(s string) *onehtml.Document {
doc, err := onehtml.Parse(strings.NewReader(s))
if err != nil {
panic(err)
}
return doc
}
func main() {
doc := parseBody(`<DIV id=main class="a b a"></DIV><svg><foreignObject></foreignObject></svg>`)
div := doc.Body().FirstChild()
fmt.Println(div.TagName(), div.Name(), div.ID(), div.ClassName())
fmt.Println(slices.Collect(div.Classes()))
fmt.Println(doc.Body().LastChild().FirstChild().TagName())
}
Output: DIV div main a b a [a b] foreignObject
func (Node) TemplateContent ¶
TemplateContent returns the contents fragment of a template element. The result is invalid for any other node.
func (Node) TextContent ¶
TextContent returns the concatenated data of all text descendants of an element, document or fragment, and the data of a text or comment node.
type NodeKind ¶
type NodeKind uint8
NodeKind is the kind of a Node.
const ( // InvalidNode is the kind of the zero Node. InvalidNode NodeKind = iota // DocumentNode is the root of a document parsed as a whole. DocumentNode // FragmentNode is the root of a parsed fragment, and the contents of a // template element. FragmentNode // DoctypeNode is a document type declaration. DoctypeNode // ElementNode is an element. ElementNode // TextNode is a run of character data. TextNode // CommentNode is a comment. CommentNode // ProcessingInstructionNode is a processing instruction, "<?target data?>". ProcessingInstructionNode )
The kinds of node a parsed document holds.
type Origin ¶
type Origin uint8
Origin is the origin of a style sheet in the cascade (CSS Cascade 5, section 6.4).
const ( // OriginUserAgent is the HTML standard's default style sheet. OriginUserAgent Origin = iota // OriginUser is a style sheet the caller supplied as the user's. OriginUser // OriginAuthor is every style sheet of the page, its style attributes and // its presentational hints. OriginAuthor )
Origins, from the weakest normal declarations to the strongest.
type ParseError ¶
type ParseError struct {
// Code is the standard's name of the error, for example
// "unexpected-null-character". Tree construction errors, which the
// standard does not name individually, use the codes "unexpected-token",
// "unexpected-start-tag", "unexpected-end-tag", "unexpected-eof",
// "unexpected-character", "foster-parenting" and "misnested-tag".
Code string
// Offset is the byte offset in [Document.Source] of the character being
// read when the error was detected, or the end of input.
Offset int
// TextOffset is the same position as an offset in [Document.Text].
TextOffset int
// TreeConstruction is true for an error found by tree construction (a
// token in the wrong place) and false for one found by the tokenizer or
// in preparing the input stream, which are the errors the standard names
// one by one.
TreeConstruction bool
}
ParseError is a parse error the standard defines. Parse errors never stop parsing: the parser recovers as the standard says and records them.
func (ParseError) Error ¶
func (e ParseError) Error() string
Error implements error, so a parse error can be reported as one.
func (ParseError) String ¶
func (e ParseError) String() string
String returns the error code and the byte offset, for example "unexpected-null-character at byte 12".
type ParseOption ¶
type ParseOption func(*config)
ParseOption configures a parse.
func WithContentType ¶
func WithContentType(header string) ParseOption
WithContentType gives the transport's Content-Type header. A charset parameter that names a known encoding is certain, as WithEncoding's label is, but ranks below it: the header is used only when no usable WithEncoding label is given. Parameter names and encoding labels are matched ignoring ASCII case, and the value may be quoted. A header with no charset, or an unknown one, is ignored.
func WithDefaultEncoding ¶
func WithDefaultEncoding(label string) ParseOption
WithDefaultEncoding names the encoding used when nothing decides: no byte order mark, no transport charset and no <meta> in the prescan. The default is windows-1252, as the standard recommends for unlabelled content; a <meta> met later while parsing still replaces it. An unknown label is ignored. Fragment parsing ignores it.
func WithEncoding ¶
func WithEncoding(label string) ParseOption
WithEncoding names the encoding the transport layer declared (the charset of a Content-Type header), by any label of the Encoding Standard. It is certain: a <meta> cannot change it, though a byte order mark still wins. It also ranks above the charset of WithContentType. An unknown label is ignored. Fragment parsing always reads UTF-8 and ignores this option.
Example ¶
A byte order mark, a transport label or a <meta> choose the encoding.
package main
import (
"fmt"
"recursiveai.org/go/onehtml"
)
func main() {
doc, _ := onehtml.ParseBytes([]byte("<p>caf\xe9"), onehtml.WithEncoding("windows-1252"))
fmt.Println(doc.Encoding(), doc.Body().TextContent())
}
Output: windows-1252 café
func WithLimits ¶
func WithLimits(l Limits) ParseOption
WithLimits replaces the limits; see Limits for the defaults.
func WithPrescanLimit ¶
func WithPrescanLimit(n int) ParseOption
WithPrescanLimit sets how many bytes the <meta> prescan reads. The default is 1024, the standard's number; a value of zero or less selects it. A <meta> beyond the limit is still honoured when the parser meets it, which restarts the parse with that encoding.
func WithScripting ¶
func WithScripting(enabled bool) ParseOption
WithScripting sets the parser's scripting flag, which decides how noscript content parses: as markup (the default, false) or as raw text (true, as in a browser that runs script). The library never runs script either way.
type PointerKind ¶
type PointerKind string
PointerKind is the value of the pointer and any-pointer media features.
const ( PointerFine PointerKind = "" PointerCoarse PointerKind = "coarse" PointerNone PointerKind = "none" )
The values of pointer and any-pointer. The zero value is a fine pointer, as on a desktop.
type PropertyRegistration ¶ added in v1.1.0
type PropertyRegistration struct {
// Name is the custom property's name, "--name".
Name string
// Syntax is the syntax string as written, "*" for any value.
Syntax string
// Inherits is the inherits descriptor.
Inherits bool
// InitialValue is the computed initial value; HasInitialValue is false
// when the rule has none, which only the universal syntax allows.
InitialValue string
HasInitialValue bool
}
PropertyRegistration is an @property rule: the syntax, inheritance and initial value of a registered custom property (CSS Properties and Values API 1).
type Provenance ¶
type Provenance uint8
Provenance is the set of ways a node came to exist other than being written plainly in the source.
const ( // ProvImplied: the parser inserted the element as if a start tag had been // written (html, head, body, tbody, an end tag's missing p or br). ProvImplied Provenance = 1 << iota // ProvCloned: the element is a copy made by the adoption agency algorithm // or by reconstructing the active formatting elements. ProvCloned // ProvReparented: foster parenting or the adoption agency moved the node. ProvReparented // ProvAttrsMerged: a later html or body start tag added attributes. ProvAttrsMerged // ProvSelfClosing: the start tag was written with a solidus. ProvSelfClosing // ProvMergedText: a text node joined text from tokens that were not next to // each other in the source. ProvMergedText // ProvSynthesized: the node was made with no source of its own and is // neither implied nor a formatting clone (a selectedcontent copy, or a // node an edit created). ProvSynthesized )
The provenance flags.
func (Provenance) Has ¶
func (p Provenance) Has(q Provenance) bool
Has reports whether every flag of q is set in p.
func (Provenance) String ¶
func (p Provenance) String() string
String lists the set flags in kebab case, comma separated, in flag order; it is "" for a node written plainly.
type QueryOption ¶
type QueryOption func(*queryConfig)
QueryOption configures a query or a Matcher.
func WithFormStates ¶
func WithFormStates(fs FormStates) QueryOption
WithFormStates overrides what the markup says about checkedness, disabledness and indeterminacy of controls, as a form the user has changed would. Without it the markup decides.
func WithScope ¶
func WithScope(n Node) QueryOption
WithScope sets the element that :scope (and the nesting selector) stands for. The queries of a node default to that node.
func WithState ¶
func WithState(f func(n Node, s InteractionState) bool) QueryOption
WithState supplies the interaction state of elements: whether n is hovered, active, focused, focus-visible or contains focus. Without it, :hover, :active, :focus, :focus-visible and :focus-within never match. :visited is static and never matches.
Example ¶
The hover, focus and active states come from the caller.
package main
import (
"fmt"
"strings"
"recursiveai.org/go/onehtml"
)
const exampleHTML = `<ul id=menu><li class=on><a href=/a>A</a><li><a href=/b>B</a><li class=on><a>C</a></ul>`
func main() {
doc, _ := onehtml.Parse(strings.NewReader(exampleHTML))
second, _ := doc.SelectFirst("li:nth-child(2)")
hovered, _ := doc.Select("li:hover", onehtml.WithState(func(n onehtml.Node, s onehtml.InteractionState) bool {
return n == second && s == onehtml.StateHover
}))
fmt.Println(len(hovered))
}
Output: 1
func WithTargetFragment ¶
func WithTargetFragment(fragment string) QueryOption
WithTargetFragment gives the fragment of the document's URL, without the "#". The element it names (the first element in tree order whose id equals it, else the first a element whose name does, trying the fragment percent-decoded when it is not found as written) is the one :target matches. Without it nothing is the target.
Example ¶
package main
import (
"fmt"
"strings"
"recursiveai.org/go/onehtml"
)
func main() {
doc, _ := onehtml.Parse(strings.NewReader(`<h2 id=intro>Intro</h2><h2 id=usage>Usage</h2>`))
t, _ := doc.SelectFirst(":target", onehtml.WithTargetFragment("usage"))
fmt.Println(t.TextContent())
}
Output: Usage
type QuirksMode ¶
type QuirksMode uint8
QuirksMode is a document's compatibility mode, set by its doctype.
const ( // NoQuirks is standards mode. NoQuirks QuirksMode = iota // LimitedQuirks is limited-quirks ("almost standards") mode. LimitedQuirks // Quirks is quirks mode. Quirks )
The compatibility modes.
func (QuirksMode) String ¶
func (q QuirksMode) String() string
String returns "no-quirks", "limited-quirks" or "quirks".
type ReplayDetail ¶
type ReplayDetail struct {
// UsedAnchor reports that the target's anchor still held and named the
// element, rather than the locator and fingerprint.
UsedAnchor bool
// PathMatched reports that the target's saved path hash equals the
// resolved element's. It is advisory: a locator that stands alone
// ([Replay] documents which) is accepted when the path differs.
PathMatched bool
// Node is the element the target resolved to; it is the zero Node for a
// target that is not an element (text, comment or rule).
Node Node
// Meta is the edit's meta value as compact JSON, or nil.
Meta json.RawMessage
}
ReplayDetail says how Replay found the target of one saved edit.
type ReplayOption ¶
type ReplayOption func(*replayConfig)
ReplayOption configures Replay.
func WithRewriteOptions ¶
func WithRewriteOptions(opts ...RewriteOption) ReplayOption
WithRewriteOptions passes options to the Rewrite that Replay makes the edits with, such as WithMaxEdits.
func WithSheets ¶
func WithSheets(sheets ...*Stylesheet) ReplayOption
WithSheets gives Replay the stylesheets saved edits may target besides the <style> elements of the document, each found by its WithSheetName.
type ReplayResult ¶
type ReplayResult struct {
// Outcomes and Reasons have one entry per saved edit. A transaction with
// any outcome other than [EditApplied] applied nothing.
Outcomes []EditOutcome
Reasons []string
// Document holds the document's bytes after the edits, when a document was
// given and every edit applied; the input bytes if no edit changed them.
Document []byte
// Sheets holds, when every edit applied, the bytes of every stylesheet
// that was given, by name, edited or not.
Sheets map[string][]byte
// Ranges lists the rewritten regions of the document.
Ranges []EditedRange
// Details has one entry per saved edit, saying how its target was found.
// An edit whose target was not resolved has the zero detail.
Details []ReplayDetail
// Rewrite is the result of the [Rewrite] that made the edits: the
// verification count, the tree changes and the stylesheet reports. It is
// nil when some edit did not resolve, so that nothing was rewritten.
Rewrite *RewriteResult
}
ReplayResult is what Replay did with a saved transaction.
func Replay ¶
func Replay(d *Document, f *EditFile, opts ...ReplayOption) *ReplayResult
Replay resolves each saved edit against d and the stylesheets, which are named by WithSheetName or, for the <style> elements of d, "inline:<n>", and, when every edit resolved and fits its target, makes them with Rewrite. Resolution follows the edit format: an anchor that still holds identifies the target (unless the locator selects exactly one different element, which is stale), otherwise the locator must select exactly one element (none is stale, several are ambiguous) whose fingerprint must agree. Nothing is guessed. d may be nil for an envelope that edits only stylesheets, and a nil f is an envelope with no edits.
Example ¶
ReadEditFile reads the family's JSON edit format and Replay applies it, finding each target again by its locator and fingerprint.
package main
import (
"fmt"
"recursiveai.org/go/onehtml"
)
func main() {
const saved = `{"format":"onehtml-edits","version":1,"edits":[
{"op":"setAttribute","target":{"locator":"#a","fingerprint":{"tag":"p","attrs":{"id":"a"}}},"name":"class","value":"done"},
{"op":"remove","target":{"locator":"#gone","fingerprint":{"tag":"p"}}}]}`
file, err := onehtml.ReadEditFile([]byte(saved))
if err != nil {
panic(err)
}
doc, _ := onehtml.ParseBytes([]byte(`<p id=a>x</p>`))
res := onehtml.Replay(doc, file)
fmt.Println(res.Outcomes)
fmt.Println(res.Reasons[1])
}
Output: [notAttempted stale] the locator selects nothing
func (*ReplayResult) Applied ¶
func (r *ReplayResult) Applied() bool
Applied reports whether every edit applied.
type ResolvedKeyframe ¶
type ResolvedKeyframe struct {
// Offset is from 0 to 1.
Offset float64
// TimingFunction is the keyframe's own, else the animation's.
TimingFunction string
// Composition is the keyframe's own, or "" when it sets none. An implicit
// keyframe has "replace".
Composition string
// Implicit is true for a 0% or 100% keyframe the rule does not have: the
// parser made it from the element's computed values.
Implicit bool
// Values holds a value for each animated property the keyframe has, sorted
// by property. The 0% and 100% keyframes have every animated property: what
// they lack gets the element's computed value.
Values []KeyframeValue
}
ResolvedKeyframe is one keyframe of an animation.
type ResolvedKeyframes ¶
type ResolvedKeyframes struct {
// Name is the animation name.
Name string
// TimingFunction and Composition are the animation's own, from the
// element's animation-timing-function and animation-composition lists
// (repeated to the length of the animation-name list).
TimingFunction, Composition string
// AnimatedProperties are the physical longhands any keyframe sets, sorted
// by name. Logical properties are mapped under the element's writing mode
// and direction.
AnimatedProperties []string
// Keyframes are ordered by offset. Blocks with one offset are one keyframe,
// a later declaration of a property winning. With no animated property there
// are none.
Keyframes []ResolvedKeyframe
}
ResolvedKeyframes is what one animation of an element is made of: the keyframes of the rule its name refers to, completed as CSS Animations 1, section 3, says. See Styles.ResolveAnimations.
type RewriteOption ¶
type RewriteOption func(*rewriteConfig)
RewriteOption configures Rewrite; WithRewriteOptions passes the same options to Replay.
func WithMaxEdits ¶
func WithMaxEdits(n int) RewriteOption
WithMaxEdits sets the most edits one transaction may hold. The default is 100,000; n must be positive (anything else keeps the default). A longer list is refused before any work: the first edit is EditFailed and the rest EditNotAttempted.
func WithMaxInsertedLength ¶
func WithMaxInsertedLength(n int) RewriteOption
WithMaxInsertedLength sets the most bytes of inserted markup, text, values and rule text one transaction may carry. The default is 16 MiB; n must be positive (anything else keeps the default). A larger transaction is refused like one over WithMaxEdits.
func WithMaxVerifications ¶
func WithMaxVerifications(n int) RewriteOption
WithMaxVerifications sets how many times the output may be parsed again while the rewrite checks itself and widens regions that do not verify. The default is 64; n must be positive (anything else keeps the default). When the count runs out the edit being widened is EditFailed and nothing is written. Every edited stylesheet is always checked whole, so there is no narrower check to opt out of.
type RewriteResult ¶
type RewriteResult struct {
// Outcomes and Reasons have one entry per edit. Reason is empty for an
// applied edit.
Outcomes []EditOutcome
Reasons []string
// Document holds the document's bytes after the edits: the input bytes
// when no edit changed it. It is nil when a document was not given or
// some edit was not applied.
Document []byte
// Sheets maps each edited linked stylesheet to its bytes after the edits.
Sheets map[*Stylesheet][]byte
// Ranges lists the rewritten regions of the document, sorted.
Ranges []EditedRange
// Verifications counts how many times the output was parsed again to
// check it: 0 for an empty transaction or one that touches no document
// bytes, 1 when no region had to be widened.
Verifications int
// Changes is the net change the edits make to the document's tree, as
// an [Editor] would report it: Old is d and New the tree the output
// parses to. It is nil when there is no document or some edit was not
// applied.
Changes *ChangeSet
// SheetReports describes each edited stylesheet, in the order the
// stylesheets first appear in the edits; the <style> elements of the
// document are included. It is empty when some edit was not applied.
SheetReports []SheetReport
}
RewriteResult is what Rewrite did.
func Rewrite ¶
func Rewrite(d *Document, edits []Edit, opts ...RewriteOption) *RewriteResult
Rewrite makes the edits and writes the result as bytes, changing only the bytes the edits touch: an unedited document comes back byte for byte, an edited one has splices at the edited ranges and nothing else different, written in the document's encoding. d may be nil when every edit is a stylesheet edit of a linked sheet. All edits apply or none does.
Each splice is checked: the output is parsed again and must give the tree the edits should have made; a splice that does not is widened to the nearest enclosing element that has bytes of its own and rewritten from the expected tree (EditedRange.Level), as the edit format describes, and an edit that no enclosing element can express is EditFailed. The input of Rewrite is never modified. For edits saved as JSON see Replay.
Example ¶
Rewrite changes only the bytes an edit touches: the odd quoting, case and entities elsewhere in the page come back exactly as they were.
package main
import (
"fmt"
"recursiveai.org/go/onehtml"
)
func main() {
src := `<P CLASS = 'a'>café</P><p id=x>old</p>`
doc, _ := onehtml.ParseBytes([]byte(src))
p, _ := doc.SelectFirst("#x")
res := onehtml.Rewrite(doc, []onehtml.Edit{
onehtml.ReplaceText(p, "new"),
onehtml.SetAttribute(p, "lang", "en"),
})
fmt.Println(res.Applied())
fmt.Println(string(res.Document))
}
Output: true <P CLASS = 'a'>café</P><p id=x lang='en'>new</p>
Example (Outcomes) ¶
A transaction applies all of its edits or none. An edit that does not fit its target is invalid, and the others are not attempted.
package main
import (
"fmt"
"recursiveai.org/go/onehtml"
)
func main() {
doc, _ := onehtml.ParseBytes([]byte(`<p id=a>x</p><br id=b>`))
a, _ := doc.SelectFirst("#a")
b, _ := doc.SelectFirst("#b")
res := onehtml.Rewrite(doc, []onehtml.Edit{
onehtml.SetAttribute(a, "title", "t"),
onehtml.AppendHTML(b, "<i>no</i>"), // a void element has no content
})
fmt.Println(res.Outcomes, res.Document == nil)
}
Output: [notAttempted invalid] true
func (*RewriteResult) Applied ¶
func (r *RewriteResult) Applied() bool
Applied reports whether every edit was applied.
type Rule ¶
type Rule struct {
// contains filtered or unexported fields
}
Rule is a handle to a rule of a Stylesheet: a style rule or an at-rule, nested ones included.
func (Rule) Declarations ¶
func (r Rule) Declarations() iter.Seq[Declaration]
Declarations iterates over the rule's own declarations in source order.
func (Rule) Index ¶
Index returns the position of r among the sheet's rules that have the same Selector and AtRules.
func (Rule) Selector ¶
Selector returns the rule's prelude with white space runs collapsed to one space, or "@name prelude" for an at-rule, the name lower-cased.
func (Rule) Sheet ¶
func (r Rule) Sheet() *Stylesheet
Sheet returns the stylesheet the rule belongs to.
func (Rule) Span ¶
Span returns the byte range of the rule in the bytes of Stylesheet.Bytes.
type SavedEdit ¶
type SavedEdit struct {
Op string
Target *Target
Name string
Value string
Text string
HTML string
Count int
Property string
// Important is the "important" flag of setStyle and setDeclaration.
Important bool
CSS string
// Before, After and End place an insertRule next to a rule target;
// EndOfSheet is `"end": true`, with the sheet named by Sheet.
Before, After, End *Target
EndOfSheet bool
Sheet string
// Meta is the edit's opaque meta value as compact JSON, or nil.
Meta json.RawMessage
// contains filtered or unexported fields
}
SavedEdit is one edit of an envelope. Which members matter depends on Op: "setAttribute" (Name, Value), "removeAttribute" (Name), "replaceText" (Text), "insertBefore", "insertAfter", "prepend", "append", "replace" (HTML), "wrap" (HTML, Count), "unwrap", "remove", "setStyle" and "setDeclaration" (Property, Value, Important), "removeStyle" and "removeDeclaration" (Property), "insertRule" (CSS and one of Before, After, End or EndOfSheet with Sheet), "removeRule", and "replaceRule" (CSS).
A member the file did not have is the zero value; Has reports which were present, since "name": "" differs from no name.
func (*SavedEdit) Has ¶
func (e *SavedEdit) Has(m SavedMember) bool
Has reports whether the edit has all the members in the bit set m (MemberName, MemberValue, …).
func (*SavedEdit) Set ¶
func (e *SavedEdit) Set(m SavedMember)
Set marks members as present; use it when building an edit by hand.
type SavedMember ¶
type SavedMember uint16
SavedMember names a member of a SavedEdit that the edit file may or may not have, for SavedEdit.Has and SavedEdit.Set. Several combine with |.
const ( MemberName SavedMember = 1 << iota MemberValue MemberText MemberHTML MemberCount MemberProperty MemberImportant MemberCSS MemberSheet )
The members of a SavedEdit that can be absent.
type Selector ¶
type Selector struct {
// contains filtered or unexported fields
}
Selector is a compiled Selectors Level 4 selector list. Compile once and reuse it: a Selector is immutable and safe for concurrent use. Make one with CompileSelector; the zero Selector and a nil *Selector are empty lists that match nothing.
func CompileComplexSelector ¶
func CompileComplexSelector(src string, opts ...SelectorOption) (*Selector, error)
CompileComplexSelector parses src as exactly one complex selector, the form CSS Conditional 4 allows inside @supports selector(): no comma list and no leading combinator. Unlike CompileSelector it reports a list of several selectors as a syntax error. Pseudo-elements are valid; an unknown pseudo-class is not.
Example ¶
@supports selector() takes exactly one complex selector.
package main
import (
"fmt"
"recursiveai.org/go/onehtml"
)
func main() {
for _, src := range []string{"a > b", "a, b", ":nonsense"} {
_, err := onehtml.CompileComplexSelector(src)
fmt.Println(src, err == nil)
}
}
Output: a > b true a, b false :nonsense false
func CompileSelector ¶
func CompileSelector(src string, opts ...SelectorOption) (*Selector, error)
CompileSelector parses src as a selector list. Case sensitivity follows HTML: type selectors and attribute names match ASCII case-insensitively on HTML elements. A selector that does not parse, or that exceeds a limit, gives an error matching ErrSelectorSyntax or ErrSelectorLimit; it never matches silently wrong. Pseudo-elements parse and never match an element in Selector.All, Selector.Matches and friends; the cascade reads them with Selector.PseudoElement.
Example ¶
Selectors that do not parse are errors, never silent mismatches.
package main
import (
"errors"
"fmt"
"recursiveai.org/go/onehtml"
)
func main() {
_, err := onehtml.CompileSelector("li >")
fmt.Println(errors.Is(err, onehtml.ErrSelectorSyntax))
sel, _ := onehtml.CompileSelector("A#x > .y:not(b)")
fmt.Println(sel, sel.Specificity(0))
}
Output: true A#x > .y:not(b) {1 1 2}
func MustCompileSelector ¶
func MustCompileSelector(src string, opts ...SelectorOption) *Selector
MustCompileSelector is like CompileSelector and panics on error. It is meant for selectors written in source code.
func (*Selector) All ¶
All returns the elements under root (not root itself) that match s, in document order, each once: querySelectorAll. :scope is root when it is an element, and the document element when root is a document.
Example ¶
Compile once, query many times; the selector is immutable and shareable.
package main
import (
"fmt"
"strings"
"recursiveai.org/go/onehtml"
)
const exampleHTML = `<ul id=menu><li class=on><a href=/a>A</a><li><a href=/b>B</a><li class=on><a>C</a></ul>`
func main() {
doc, _ := onehtml.Parse(strings.NewReader(exampleHTML))
sel := onehtml.MustCompileSelector("li:nth-child(odd) a")
for a := range sel.All(doc.Root()) {
fmt.Println(a.TextContent())
}
}
Output: A C
func (*Selector) Closest ¶
func (s *Selector) Closest(n Node, opts ...QueryOption) Node
Closest returns n or its nearest ancestor that matches s, or the zero Node: Element.closest. :scope is n unless WithScope says otherwise.
func (*Selector) First ¶
func (s *Selector) First(root Node, opts ...QueryOption) Node
First returns the first element under root that matches s, or the zero Node: querySelector.
func (*Selector) Matches ¶
func (s *Selector) Matches(n Node, opts ...QueryOption) bool
Matches reports whether n matches s: Element.matches. :scope is n unless WithScope says otherwise.
func (*Selector) PseudoElement ¶
PseudoElement returns the lower-case name of the pseudo-element the i-th complex selector ends in (for example "before"), or "" when it has none.
func (*Selector) Specificity ¶
func (s *Selector) Specificity(i int) Specificity
Specificity returns the specificity of the i-th complex selector.
type SelectorLimitError ¶
type SelectorLimitError struct {
// Limit names the limit, one of the LimitSelector… constants or
// [LimitInputSize].
Limit string
// Max is the value that was exceeded.
Max int
}
SelectorLimitError reports a selector that is larger or deeper than a limit allows. It matches ErrSelectorLimit and ErrLimit.
func (*SelectorLimitError) Error ¶
func (e *SelectorLimitError) Error() string
Error describes the limit that was exceeded.
func (*SelectorLimitError) Is ¶
func (e *SelectorLimitError) Is(target error) bool
Is reports a match with ErrSelectorLimit and ErrLimit.
type SelectorLimits ¶
type SelectorLimits struct {
// MaxInput is the longest selector text in bytes. Default 65536.
MaxInput int
// MaxNesting is how deep :is(), :where(), :not(), :has() and the
// "of S" of :nth-child() may nest. Default 16.
MaxNesting int
// MaxCompounds is the most compound selectors in one complex selector.
// Default 128.
MaxCompounds int
// MaxSelectors is the most complex selectors in one list. Default 4096.
MaxSelectors int
// MaxSimples is the most simple selectors in one selector. Default 16384.
MaxSimples int
}
SelectorLimits bound the size of a selector. A zero field selects its default; each limit is checked before the work it guards.
type SelectorOption ¶
type SelectorOption func(*selectorConfig)
SelectorOption configures CompileSelector.
func WithNamespaces ¶
func WithNamespaces(prefixes map[string]string) SelectorOption
WithNamespaces declares the namespace prefixes a selector may use. The empty prefix names the default namespace for type selectors that have no prefix. Without this option a prefix is a syntax error and type selectors match in any namespace. Namespaces are compared by URI; the URIs of HTML, SVG and MathML are those in Namespace.URI.
func WithSelectorLimits ¶
func WithSelectorLimits(l SelectorLimits) SelectorOption
WithSelectorLimits replaces the default selector limits.
type SelectorSyntaxError ¶
type SelectorSyntaxError struct {
// Pos is the byte offset in the selector text of the problem.
Pos int
// Msg says what is wrong.
Msg string
}
SelectorSyntaxError reports selector text that does not parse. It matches ErrSelectorSyntax.
func (*SelectorSyntaxError) Error ¶
func (e *SelectorSyntaxError) Error() string
Error describes the problem and where it is.
func (*SelectorSyntaxError) Is ¶
func (e *SelectorSyntaxError) Is(target error) bool
Is reports a match with ErrSelectorSyntax.
type SheetInfo ¶
type SheetInfo struct {
// Origin is the sheet's origin.
Origin Origin
// URL is the sheet's absolute URL; empty for a <style> element and for the
// user agent and user sheets.
URL string
// Owner is the <style> or <link> element that brought the sheet in; the
// zero Node for the user agent sheet, user sheets and imports.
Owner Node
// ImportedBy is the index in [Styles.Sheets] of the sheet that imported
// this one, or -1.
ImportedBy int
}
SheetInfo describes a style sheet that took part in the cascade.
type SheetReport ¶
type SheetReport struct {
// Sheet is the stylesheet as it was given.
Sheet *Stylesheet
// Bytes holds the stylesheet's bytes after the edits, in its encoding;
// for a <style> element it is nil (the text is in the document's bytes).
Bytes []byte
// Text is the stylesheet's text after the edits.
Text string
// Added, Removed and Changed list rule indexes in ascending order. A
// change to a declaration counts as a change of its rule.
Added, Removed, Changed []int
// Ranges are the changed ranges of the stylesheet's text: Old in the
// text before, New the text that replaced it.
Ranges []EditedRange
}
SheetReport describes what a transaction did to one stylesheet. Rules are numbered by their Rule.Index in the stylesheet before the edit (Removed, Changed) or after it (Added).
type SniffResult ¶
type SniffResult struct {
// Encoding is the standard name of the encoding, for example "UTF-8" or
// "windows-1252".
Encoding string
// Certain is true when a byte order mark, [WithEncoding] or
// [WithContentType] decided, so that no <meta> can change it. It is false
// for a <meta> found by the prescan and for the default, which a <meta>
// met later in the parse may still replace.
Certain bool
// BOMLength is the length of the byte order mark at the start of the
// input, which the parser skips; 0 when there is none.
BOMLength int
}
SniffResult is the outcome of SniffEncoding.
func SniffEncoding ¶
func SniffEncoding(b []byte, opts ...ParseOption) SniffResult
SniffEncoding reports the encoding Parse starts decoding b with, before any markup is parsed: a byte order mark first, then the WithEncoding label, then the charset of WithContentType, then a <meta> declaration in the first bytes (1024, or WithPrescanLimit), then the WithDefaultEncoding label, then windows-1252. Other options are ignored. A parse may still change a tentative result when it meets a <meta> beyond the prescan; the final answer is Document.Encoding.
Example ¶
package main
import (
"fmt"
"recursiveai.org/go/onehtml"
)
func main() {
page := []byte(`<meta charset="koi8-r"><p>`)
// The <meta> in the first bytes is a guess: tentative.
r := onehtml.SniffEncoding(page)
fmt.Println(r.Encoding, r.Certain)
// A transport charset is certain and beats the <meta>.
r = onehtml.SniffEncoding(page, onehtml.WithContentType("text/html; charset=windows-1251"))
fmt.Println(r.Encoding, r.Certain)
// A byte order mark beats everything.
r = onehtml.SniffEncoding([]byte("\xef\xbb\xbf<p>"), onehtml.WithEncoding("koi8-r"))
fmt.Println(r.Encoding, r.Certain, r.BOMLength)
}
Output: KOI8-R false windows-1251 true UTF-8 true 3
type Source ¶
type Source struct {
// Initial is true when nothing set the property and its initial value
// applies; Inherited when the value is the parent's. Kind is zero in both
// cases, and the fields below are empty.
Initial, Inherited bool
// Kind is what kind of declaration supplied the value.
Kind SourceKind
// Origin is the origin of the winning declaration: the user agent, the
// user or the author (a style attribute and a hint are the author's).
Origin Origin
// Important is true for a declaration marked !important.
Important bool
// Layer is the dotted name of the cascade layer of a sheet rule, empty when
// unlayered.
Layer string
// Selector is the selector list of the winning rule as written. It is
// empty for a style attribute and a hint.
Selector string
// Sheet is the index in [Styles.Sheets] of the sheet the rule is in, and
// SheetURL its URL (empty for a <style> element and for sheets without
// one); both are zero for a style attribute and a hint.
Sheet int
SheetURL string
}
Source says where the computed value of a property came from.
type SourceKind ¶
type SourceKind uint8
SourceKind says what kind of declaration supplied a computed value.
const ( // SourceSheet is a declaration of a style rule in a style sheet. SourceSheet SourceKind = iota + 1 // SourceInline is a declaration of the element's style attribute. SourceInline // SourceHint is a declaration a presentational attribute stands for. SourceHint )
The kinds of declaration source.
func (SourceKind) String ¶
func (k SourceKind) String() string
String returns "sheet", "inline" or "hint".
type Span ¶
type Span struct{ Start, End int }
Span is a half-open byte range [Start, End) of the original input bytes. A Span with Start < 0 is absent: the parser made the thing it describes without source text for it (an implied <tbody>, for example).
type Specificity ¶
type Specificity struct{ A, B, C uint32 }
Specificity is the (A, B, C) triple of Selectors Level 4, section 17.
func (Specificity) Compare ¶
func (s Specificity) Compare(o Specificity) int
Compare returns -1, 0 or 1 as s is less than, equal to or greater than o.
type StyleContext ¶
type StyleContext struct {
// Print evaluates media queries for the print media type instead of screen.
Print bool
// ViewportWidth and ViewportHeight are the viewport in CSS px (default
// 1280 x 720). They decide the width and height media features and the
// viewport units.
ViewportWidth, ViewportHeight float64
// DarkScheme is prefers-color-scheme: dark; it also selects the dark side
// of light-dark().
DarkScheme bool
// ReducedMotion is prefers-reduced-motion: reduce.
ReducedMotion bool
// Contrast is prefers-contrast.
Contrast Contrast
// ForcedColors is forced-colors: active.
ForcedColors bool
// DevicePixelRatio is the resolution in device pixels per CSS px, which
// the resolution media feature reads (default 1).
DevicePixelRatio float64
// ReducedTransparency and ReducedData are prefers-reduced-transparency:
// reduce and prefers-reduced-data: reduce.
ReducedTransparency, ReducedData bool
// NoHover and NoAnyHover make the hover and any-hover media features
// "none" instead of "hover".
NoHover, NoAnyHover bool
// Pointer and AnyPointer are the pointer and any-pointer media features
// (default fine).
Pointer, AnyPointer PointerKind
// ColorBits is the display's bits per colour component, which the color
// media feature reads (default 8). Monochrome makes the display
// monochrome: color is 0 and monochrome is 8.
ColorBits int
Monochrome bool
// Focus is the focused element, and FocusSource how it got focus. The
// element matches :focus, and it and its ancestors match :focus-within.
Focus Node
FocusSource FocusSource
// Hover is the hovered element. It and its ancestors match :hover, and so
// does the control a hovered <label> labels.
Hover Node
// Active is the element being activated, matched by :active like :hover.
Active Node
// TargetFragment is the fragment of the document's URL, without "#", which
// :target and :target-within read.
TargetFragment string
// Forms overrides what the markup says about checked, disabled and
// indeterminate controls, as the user's changes to a form would.
Forms FormStates
}
StyleContext is what the cascade needs to know about the output and the user: the media features that @media rules read, and the interaction state that :hover, :focus and the like read. The zero value is a 1280 x 720 light-scheme screen with no preferences and nothing hovered, focused or active.
Example ¶
Media features and the viewport come from the StyleContext.
package main
import (
"fmt"
"strings"
"recursiveai.org/go/onehtml"
)
const exampleStyled = `<!DOCTYPE html>
<style>
body { color: #333; font-size: 20px }
h1 { color: navy }
.note { color: gray; margin-left: 2em }
@media (min-width: 800px) { .note { color: black } }
</style>
<h1 id=title>Title</h1><p class=note id=n style="padding-top: 1em">A note</p>`
func main() {
doc, _ := onehtml.Parse(strings.NewReader(exampleStyled))
note, _ := doc.SelectFirst("#n")
for _, width := range []float64{500, 1000} {
styles := doc.Style(onehtml.WithStyleContext(onehtml.StyleContext{ViewportWidth: width}))
fmt.Println(width, styles.ComputedStyle(note).Get("color"))
}
}
Output: 500 rgb(128, 128, 128) 1000 rgb(0, 0, 0)
Example (Forms) ¶
package main
import (
"fmt"
"strings"
"recursiveai.org/go/onehtml"
)
func main() {
doc, _ := onehtml.Parse(strings.NewReader(`<style>input:checked + label { color: green }</style><input id=c type=checkbox><label id=l>Agree</label>`))
c, _ := doc.SelectFirst("#c")
l, _ := doc.SelectFirst("#l")
for _, checked := range []bool{false, true} {
forms := onehtml.FormStates{}.WithChecked(c, checked)
styles := doc.Style(onehtml.WithStyleContext(onehtml.StyleContext{Forms: forms}))
fmt.Println(checked, styles.ComputedStyle(l).Get("color"))
}
}
Output: false rgb(0, 0, 0) true rgb(0, 128, 0)
type StyleDelta ¶
type StyleDelta struct {
// Property is the property name: lower case for a standard property,
// as written for a custom one.
Property string
// Old and New are the declared values, with " !important" appended when
// important. HadOld and HasNew say whether the property was declared
// before and after.
Old, New string
HadOld, HasNew bool
}
StyleDelta is one property of an element's style attribute whose declared value differs between two snapshots.
type StyleDiagnostic ¶
StyleDiagnostic reports something the cascade could not do with the page's style sources. Diagnostics never stop the cascade.
type StyleImpact ¶
type StyleImpact uint8
StyleImpact is a set of bits saying which kinds of work a commit gives a style consumer.
const ( // ImpactAttributes: an element's attributes changed. ImpactAttributes StyleImpact = 1 << iota // ImpactStructure: a subtree was inserted, removed or moved, or a child // list changed. ImpactStructure // ImpactText: character data changed. ImpactText // ImpactStyleSheets: a style, link or base element, or the doctype, was // inserted, removed or moved, or had its attributes, text or children // changed, so the sheets or the quirks mode may differ. ImpactStyleSheets )
The kinds of change in a StyleImpact.
func (StyleImpact) Has ¶
func (s StyleImpact) Has(k StyleImpact) bool
Has reports whether s includes every bit of k.
func (StyleImpact) String ¶
func (s StyleImpact) String() string
String lists the bits, for example "attributes|structure"; "none" for the empty set.
type StyleLimits ¶
type StyleLimits struct {
// MaxSheets is the most style sheets read: <style> and <link> elements,
// user sheets and imports together (default 4096).
MaxSheets int
// MaxRules is the most style rules read, in every sheet together (default 1,048,576).
MaxRules int
// MaxLayers is the most cascade layers made in one origin (default 4096).
MaxLayers int
// MaxImportDepth is how deep a chain of @import rules is followed
// (default [MaxImportDepth]).
MaxImportDepth int
}
StyleLimits lowers the limits on what the cascade gathers. A zero field keeps the default; a limit cannot be raised above the default.
type StyleOption ¶
type StyleOption func(*styleConfig)
StyleOption configures Document.Style.
func WithBaseURL ¶
func WithBaseURL(u string) StyleOption
WithBaseURL gives the document's URL, against which the href of <link> and <base> elements is resolved. Without it, relative hrefs are used as written. The first <base href> of the document changes the base for <link>.
func WithDeclarationFilter ¶
func WithDeclarationFilter(f func(property, value string) bool) StyleOption
WithDeclarationFilter lets the caller refuse declarations the library would accept: f is asked about each declaration of a style sheet or style attribute (not about presentational hints) with the property name as the library knows it (custom properties with their "--") and the value as written, trimmed. When f returns false the declaration is dropped as if it were invalid at parse time, so an earlier declaration of the property applies (CSS Cascade 5, section 4.2). f runs once per declaration while the sheets are read, and may be called from any goroutine that computes styles for a style attribute.
Example ¶
package main
import (
"fmt"
"strings"
"recursiveai.org/go/onehtml"
)
func main() {
doc, _ := onehtml.Parse(strings.NewReader(`<style>p { z-index: 1 } p { z-index: 2 }</style><p id=p>x</p>`))
p, _ := doc.SelectFirst("#p")
styles := doc.Style(onehtml.WithDeclarationFilter(func(property, value string) bool {
return !(property == "z-index" && value == "2")
}))
fmt.Println(styles.ComputedStyle(p).Get("z-index"))
}
Output: 1
func WithFontMetrics ¶ added in v1.1.0
func WithFontMetrics(f FontMetricsFunc) StyleOption
WithFontMetrics supplies font measurements for the font-relative units ex, ch, cap and ic, and rex, rch, rcap and ric. Without it, or where f returns zero, ex and ch are half an em, cap 0.7 em and ic one em (CSS Values 4, section 6.1.1, for unknown metrics). Styles.Restyle keeps the function of the styles it comes from; Styles.WithContext needs it again among its options when the media features change.
Example ¶
package main
import (
"fmt"
"strings"
"recursiveai.org/go/onehtml"
)
func main() {
doc, _ := onehtml.Parse(strings.NewReader(`<!DOCTYPE html>
<p id=a style="font: 20px Inter; margin-left: 2ex; padding-left: 3ch">`))
// The library has no fonts: the caller says how big the x-height and the
// zero are in the face it will draw the text with.
inter := func(q onehtml.FontQuery) onehtml.FontMetrics {
if q.Families[0] == "Inter" {
return onehtml.FontMetrics{XHeight: 0.55, ZeroAdvance: 0.62}
}
return onehtml.FontMetrics{}
}
for _, styles := range []*onehtml.Styles{doc.Style(), doc.Style(onehtml.WithFontMetrics(inter))} {
cs := styles.ComputedStyle(doc.ElementByID("a"))
fmt.Println(cs.Get("margin-left"), cs.Get("padding-left"))
}
}
Output: 20px 30px 22px 37.2px
func WithStyleContext ¶
func WithStyleContext(ctx StyleContext) StyleOption
WithStyleContext sets the media features and interaction state the cascade runs under; see StyleContext for the default. Styles.Restyle ignores it: the restyled cascade keeps the context of the styles it comes from.
func WithStyleLimits ¶
func WithStyleLimits(l StyleLimits) StyleOption
WithStyleLimits lowers the limits on style sources; see StyleLimits. A source that would go over a limit is skipped and reported by Styles.Diagnostics as DiagLimit.
Example ¶
package main
import (
"fmt"
"strings"
"recursiveai.org/go/onehtml"
)
func main() {
doc, _ := onehtml.Parse(strings.NewReader(`<style>p{}</style><style>p{}</style><style>p{}</style>`))
styles := doc.Style(onehtml.WithStyleLimits(onehtml.StyleLimits{MaxSheets: 2}))
fmt.Println(len(styles.Sheets())-1, styles.Diagnostics()[0].Kind)
}
Output: 2 limit
func WithStylesheetResolver ¶
func WithStylesheetResolver(r StylesheetResolver) StyleOption
WithStylesheetResolver supplies linked and imported style sheets.
Example ¶
A resolver answers for every linked or imported sheet by its absolute URL, and can serve them from anywhere the caller has them: a map, a cache, a bundle. The library calls it and never fetches.
package main
import (
"fmt"
"strings"
"recursiveai.org/go/onehtml"
)
func main() {
doc, _ := onehtml.ParseBytes([]byte(`<link rel=stylesheet href=/a.css><p id=p>x</p>`))
var asked []string
styles := doc.Style(
onehtml.WithBaseURL("https://example.com/"),
onehtml.WithStylesheetResolver(func(url string) ([]byte, bool) {
asked = append(asked, url)
if strings.HasSuffix(url, "/a.css") {
return []byte(`@import "b.css"; p { color: green }`), true
}
return []byte(`p { background-color: yellow }`), true
}))
p, _ := doc.SelectFirst("#p")
cs := styles.ComputedStyle(p)
fmt.Println(cs.Get("color"), cs.Get("background-color"))
fmt.Println(asked)
}
Output: rgb(0, 128, 0) rgb(255, 255, 0) [https://example.com/a.css https://example.com/b.css]
func WithStylesheets ¶
func WithStylesheets(sheets map[string]string) StyleOption
WithStylesheets supplies linked and imported style sheets from a map of absolute URL to the sheet's text.
Example ¶
Linked style sheets come from the caller, by absolute URL. The library never fetches; a sheet the caller lacks is a diagnostic.
package main
import (
"fmt"
"strings"
"recursiveai.org/go/onehtml"
)
func main() {
doc, _ := onehtml.Parse(strings.NewReader(`<link rel=stylesheet href=site.css><link rel=stylesheet href=gone.css><p id=p>`))
styles := doc.Style(onehtml.WithBaseURL("https://example.com/docs/page.html"),
onehtml.WithStylesheets(map[string]string{"https://example.com/docs/site.css": "p { color: green }"}))
p, _ := doc.SelectFirst("#p")
fmt.Println(styles.ComputedStyle(p).Get("color"))
for _, d := range styles.Diagnostics() {
fmt.Println(d.Kind, d.URL)
}
}
Output: rgb(0, 128, 0) missing-stylesheet https://example.com/docs/gone.css
func WithUserAgentStylesheet ¶
func WithUserAgentStylesheet(on bool) StyleOption
WithUserAgentStylesheet says whether the HTML standard's default style sheet takes part. It does by default; WithUserAgentStylesheet(false) leaves it out, so only the page's own rules apply.
func WithUserStylesheet ¶
func WithUserStylesheet(css string) StyleOption
WithUserStylesheet adds a style sheet of the user origin. It sits between the user agent sheet and the page in the cascade, and its !important declarations beat the page's.
type Styles ¶
type Styles struct {
// contains filtered or unexported fields
}
Styles is the cascade of one document under one StyleContext: it gives every element its computed style, and the rules that matched it. Elements are computed on first use, with their ancestors, and kept. A Styles is safe for concurrent use.
func (*Styles) ChangedKeyframes ¶
ChangedKeyframes returns the names of the keyframes rules whose winning definition differs between prev and s, sorted: a name that gained a rule, lost it, or has a rule that says something else. Use it after Styles.Restyle, with the styles from before the edit, to know which animations to restart. Styles of a different context compare as they are.
Example ¶
package main
import (
"fmt"
"strings"
"recursiveai.org/go/onehtml"
)
func main() {
before, _ := onehtml.Parse(strings.NewReader(`<style>@keyframes a{to{opacity:1}}@keyframes b{to{opacity:1}}</style>`))
after, _ := onehtml.Parse(strings.NewReader(`<style>@keyframes a{to{opacity:1}}@keyframes b{to{opacity:.5}}@keyframes c{to{opacity:1}}</style>`))
fmt.Println(after.Style().ChangedKeyframes(before.Style()))
}
Output: [b c]
func (*Styles) ComputedStyle ¶
func (s *Styles) ComputedStyle(n Node) *ComputedStyle
ComputedStyle returns the computed style of an element, computing it and its ancestors on first use. It is nil for a node that is not an element of the document.
func (*Styles) Context ¶
func (s *Styles) Context() StyleContext
Context returns the context the styles were computed under.
func (*Styles) Diagnostics ¶
func (s *Styles) Diagnostics() []StyleDiagnostic
Diagnostics lists what could not be read: sheets the caller did not supply, import cycles and limits.
func (*Styles) InvalidDeclarations ¶ added in v1.1.0
func (s *Styles) InvalidDeclarations() iter.Seq2[Node, InvalidDeclaration]
InvalidDeclarations walks the elements of the document in document order and yields each declaration that is invalid at computed-value time for the element it applies to (see ComputedStyle.InvalidDeclarations). It computes the style of every element it passes. Computing is lazy, so this is how to get a complete report for a page.
Example ¶
package main
import (
"fmt"
"strings"
"recursiveai.org/go/onehtml"
)
func main() {
doc, _ := onehtml.Parse(strings.NewReader(`<!DOCTYPE html>
<style>
p { --pad: 4px; padding: var(--pad) var(--missing); width: var(--pad) var(--pad) }
</style>
<p id=a>`))
for n, d := range doc.Style().InvalidDeclarations() {
id, _ := n.Get("id")
fmt.Printf("%s %s: %s (%s)\n", id, d.Property, d.Value, d.Source.Selector)
}
}
Output: a padding: var(--pad) var(--missing) (p) a width: var(--pad) var(--pad) (p)
func (*Styles) Keyframes ¶
func (s *Styles) Keyframes(name string) (*KeyframesRule, bool)
Keyframes returns the @keyframes rule the name refers to: the winning rule of the name among every rule the style sources hold, those inside @media, @supports and @layer included when they apply. The later rule of a name wins within an origin and layer, an unlayered rule beats a layered one, and the author origin beats the user origin. It reports false when no rule has the name. The result is shared; do not change it.
Example ¶
package main
import (
"fmt"
"strings"
"recursiveai.org/go/onehtml"
)
func main() {
doc, _ := onehtml.Parse(strings.NewReader(`<style>
@keyframes fade{from{opacity:0}50%,to{opacity:1;animation-timing-function:linear}}
</style>`))
rule, _ := doc.Style().Keyframes("fade")
for _, b := range rule.Blocks {
fmt.Println(b.Offset, b.TimingFunction, b.Declarations)
}
}
Output: 0 [{opacity 0 false}] 0.5 linear [{opacity 1 false}] 1 linear [{opacity 1 false}]
func (*Styles) MatchedRules ¶
func (s *Styles) MatchedRules(n Node) []MatchedRule
MatchedRules returns the style rules that match the element, from the weakest to the strongest by origin, layer, specificity and order of appearance (!important declarations reorder origins and layers, which this does not show). It leaves out the style attribute and presentational hints.
Example ¶
The low level: which rules matched, in cascade order, with their origin, layer, specificity and declarations.
package main
import (
"fmt"
"strings"
"recursiveai.org/go/onehtml"
)
func main() {
doc, _ := onehtml.Parse(strings.NewReader(`<!DOCTYPE html><style>@layer base { p { color: red } } p.k { color: blue; margin: 0 !important }</style><p class=k id=p>`))
styles := doc.Style()
p, _ := doc.SelectFirst("#p")
for _, r := range styles.MatchedRules(p) {
if r.Origin != onehtml.OriginAuthor {
continue
}
fmt.Printf("%q layer=%q specificity=%v", r.Selector, r.Layer, r.Specificity)
for _, d := range r.Declarations {
fmt.Printf(" %s:%s", d.Name, d.Value)
if d.Important {
fmt.Print("!")
}
}
fmt.Println()
}
}
Output: "p" layer="base" specificity={0 0 1} color:red "p.k" layer="" specificity={0 1 1} color:blue margin:0!
func (*Styles) PseudoStyle ¶
func (s *Styles) PseudoStyle(n Node, kind string) *ComputedStyle
PseudoStyle returns the computed style of a pseudo-element of an element, or nil when the element has none. kind is the pseudo-element's name without colons: "before", "after", "marker", "selection", "placeholder", "slider-thumb", "slider-track" or "slider-fill" (the vendor names of the slider parts in selectors, such as ::-webkit-slider-thumb, count too). Only rules whose selector ends in exactly that pseudo-element apply, and the pseudo-element inherits from its element. A pseudo-element that generates no box (its content is none or normal) still has a style here; the caller reads the content property.
A ::before or ::after has a style only when a rule styles it. A ::marker also has one on a list item (an li element or display: list-item) that no rule styles, and a ::placeholder only on an input or textarea with a non-empty placeholder attribute, the slider parts only on an input of type range. A ::selection takes only the properties highlights accept, and inherits from the ::selection of its parent element, so it has a style when any ancestor does.
func (*Styles) Registrations ¶ added in v1.1.0
func (s *Styles) Registrations() []PropertyRegistration
Registrations returns the document's valid @property rules, one per name (the last in sheet order wins), sorted by name. A custom property that is registered takes its initial value when nothing sets it, does not inherit when inherits is false, and has a value that does not match its syntax treated as unset; a keyframe that sets it is reported by ResolveAnimations so that a caller can interpolate it by its syntax.
Example ¶
package main
import (
"fmt"
"strings"
"recursiveai.org/go/onehtml"
)
func main() {
doc, _ := onehtml.Parse(strings.NewReader(`<!DOCTYPE html>
<style>
@property --gap { syntax: "<length>"; inherits: false; initial-value: 4px }
.box { margin-left: var(--gap) }
.wide { --gap: calc(2px + 1em) }
</style>
<div class=box id=a><p class="box wide" id=b>`))
styles := doc.Style()
for _, r := range styles.Registrations() {
fmt.Printf("%s %s inherits=%v initial=%s\n", r.Name, r.Syntax, r.Inherits, r.InitialValue)
}
for _, id := range []string{"a", "b"} {
cs := styles.ComputedStyle(doc.ElementByID(id))
fmt.Println(id, cs.Get("--gap"), cs.Get("margin-left"))
}
}
Output: --gap <length> inherits=false initial=4px a 4px 4px b 18px 18px
func (*Styles) ResolveAnimations ¶
func (s *Styles) ResolveAnimations(n Node) []*ResolvedKeyframes
ResolveAnimations resolves the animations of element n: one entry for each item of its animation-name list, in order, nil where the name is "none" or has no @keyframes rule. An element with the initial animation-name has one nil entry. It returns nil when n is not an element of the document.
The animation-timing-function and animation-composition lists are repeated to the length of the name list. The library runs no clock: this is the information an animation engine would start from, not an interpolation.
Example ¶
package main
import (
"fmt"
"strings"
"recursiveai.org/go/onehtml"
)
func main() {
doc, _ := onehtml.Parse(strings.NewReader(`<style>
p{opacity:.5;animation:fade 1s ease-in}
@keyframes fade{to{opacity:1}}
</style><p id=a>`))
styles := doc.Style()
for _, a := range styles.ResolveAnimations(doc.ElementByID("a")) {
for _, k := range a.Keyframes {
fmt.Println(a.Name, k.Offset, k.Implicit, k.Values)
}
}
}
Output: fade 0 true [{opacity 0.5 false}] fade 1 false [{opacity 1 false}]
func (*Styles) ResolveKeyframes ¶
func (s *Styles) ResolveKeyframes(n Node, name string) (*ResolvedKeyframes, bool)
ResolveKeyframes resolves the animation of element n that has the given name, using the timing function and composition of the first item of its animation-name list with that name (the first item when the element does not use the name). It reports false when no @keyframes rule has the name.
func (*Styles) Restyle ¶
func (s *Styles) Restyle(cs *ChangeSet, opts ...StyleOption) (*Styles, error)
Restyle returns the styles of the snapshot a commit produced, given the change set of that commit. Computed styles of elements the edit cannot have reached are kept; the others are computed again when they are read. Every style it gives is the one a fresh Document.Style on the new snapshot would give.
What an edit reaches depends on what the style rules read. A class, id or attribute change reaches the element, and from there only as far as some selector looks: ancestors' descendants, following siblings, or the elements a :has() is on. An inserted, removed or moved node reaches the siblings and parent that structural pseudo-classes (:nth-child(), :first-child, :empty, the + and ~ combinators, :has()) can see. A change to a <style>, <link> or <base> element, or to the text of a <style>, gathers the style sources again; so does passing options, which replace those of the original call. When the reach is too wide to follow, all styles are dropped, which is always correct.
The interaction state (focus, hover, active) carries over: the nodes the context names are looked up in the new snapshot, and if one is gone or the elements it affects differ, styles are computed again from scratch.
Pseudo-element styles (Styles.PseudoStyle) are never cached: each is built from the rules of the new snapshot and the element's style, so they follow the element and are always the ones a fresh call would give.
The receiver stays valid and keeps describing the old snapshot. Restyle returns ErrStaleChanges when cs does not start at that snapshot.
Example ¶
Follow edits: an edit gives a new snapshot and a change set, and Restyle turns the styles of the old snapshot into the styles of the new one, computing again only what the edit can have reached. The result equals a fresh Document.Style. A class change reaches the element, and from there only as far as some selector of the page looks.
doc, _ := onehtml.Parse(strings.NewReader(exampleStyled))
styles := doc.Style()
note, _ := doc.SelectFirst("#n")
fmt.Println(styles.ComputedStyle(note).Get("color"))
next, changes, _ := doc.Apply(onehtml.SetAttribute(note, "class", ""))
styles, _ = styles.Restyle(changes)
note = next.NodeAt(note.Index()) // a node keeps its index in later snapshots
fmt.Println(styles.ComputedStyle(note).Get("color"))
Output: rgb(0, 0, 0) rgb(51, 51, 51)
func (*Styles) Sheets ¶
Sheets lists the style sheets that took part, in order of appearance. Index 0 stands for the user agent sheet.
func (*Styles) WithContext ¶
func (s *Styles) WithContext(ctx StyleContext, opts ...StyleOption) *Styles
WithContext returns the styles under another context. When only the interaction state differs (hover, focus, active, target) the rules and shared styles are reused and elements are computed again on demand; a change of media features gathers the style sources again, using opts.
Example ¶
Interaction state is part of the context; changing it keeps the parsed rules.
package main
import (
"fmt"
"strings"
"recursiveai.org/go/onehtml"
)
func main() {
doc, _ := onehtml.Parse(strings.NewReader(`<style>a { color: blue } a:hover { color: red }</style><a id=a href=x>x</a>`))
styles := doc.Style()
a, _ := doc.SelectFirst("#a")
fmt.Println(styles.ComputedStyle(a).Get("color"))
hovered := styles.WithContext(onehtml.StyleContext{Hover: a})
fmt.Println(hovered.ComputedStyle(a).Get("color"))
}
Output: rgb(0, 0, 255) rgb(255, 0, 0)
type Stylesheet ¶
type Stylesheet struct {
// contains filtered or unexported fields
}
Stylesheet is a parsed stylesheet: either one linked from a page, whose bytes the caller supplied (ParseStylesheet), or the text of a <style> element (Document.Stylesheets). It is immutable and keeps the original bytes and the exact source range of every rule and declaration, so edits can change only what they touch. Edit it through Rewrite with the stylesheet edits (SetDeclaration, [InsertRule…], RemoveRule, ReplaceRule).
func ParseStylesheet ¶
func ParseStylesheet(b []byte, opts ...StylesheetOption) (*Stylesheet, error)
ParseStylesheet decodes and parses the bytes of a stylesheet. The encoding comes from a byte order mark, the Content-Type charset (WithSheetCharset), a @charset rule, the encoding of the linking document (WithSheetEnvironmentCharset), then UTF-8 (CSS Syntax 3.2). Malformed CSS never fails; the only error is a limit.
Example ¶
A stylesheet is edited as text: rules are addressed, declarations set, and the new bytes differ from the old ones only where the edit is.
package main
import (
"fmt"
"recursiveai.org/go/onehtml"
)
func main() {
css := "a { color: red }\n/* keep */\nb { margin: 0 }\n"
sheet, _ := onehtml.ParseStylesheet([]byte(css), onehtml.WithSheetName("site.css"))
var a onehtml.Rule
for r := range sheet.Rules() {
a = r
break
}
res := onehtml.Rewrite(nil, []onehtml.Edit{onehtml.SetDeclaration(a, "color", "blue", true)})
fmt.Print(string(res.Sheets[sheet]))
}
Output: a { color: blue !important } /* keep */ b { margin: 0 }
func (*Stylesheet) Bytes ¶
func (s *Stylesheet) Bytes() []byte
Bytes returns the bytes the sheet was parsed from; for an inline sheet, the bytes of the whole document. The caller must not modify them.
func (*Stylesheet) Encoding ¶
func (s *Stylesheet) Encoding() string
Encoding returns the standard name of the sheet's encoding.
func (*Stylesheet) Name ¶
func (s *Stylesheet) Name() string
Name returns the sheet's name in the edit format: the URL it was given, or "inline:<n>" for the n-th <style> element of a document.
func (*Stylesheet) Rules ¶
func (s *Stylesheet) Rules() iter.Seq[Rule]
Rules lists every rule of the sheet in source order, rules inside at-rules and nested style rules included. A @charset rule is not a rule.
func (*Stylesheet) Text ¶
func (s *Stylesheet) Text() string
Text returns the decoded text of the sheet.
type StylesheetOption ¶
type StylesheetOption func(*sheetConfig)
StylesheetOption configures ParseStylesheet.
func WithSheetCharset ¶
func WithSheetCharset(label string) StylesheetOption
WithSheetCharset gives the charset of the Content-Type the sheet was served with. It takes precedence over a @charset rule, as the CSS Syntax standard orders the sources of an encoding.
func WithSheetEnvironmentCharset ¶
func WithSheetEnvironmentCharset(label string) StylesheetOption
WithSheetEnvironmentCharset gives the encoding of the document that links the sheet. It is the last resort before UTF-8, used when neither a byte order mark, the Content-Type charset nor a @charset rule decides (CSS Syntax 3.2).
func WithSheetName ¶
func WithSheetName(name string) StylesheetOption
WithSheetName sets the name the edit format uses for the sheet, usually the URL it was linked by.
type StylesheetResolver ¶
StylesheetResolver gives the bytes of the style sheet at an absolute URL, or false when the caller does not have it. The library never fetches: every linked or imported sheet comes through here.
type Target ¶
type Target struct {
Kind string
Locator string
Fingerprint *Fingerprint
Anchor *Anchor
Parent *Target
Index int
HasIndex bool
Sheet string
Selector string
AtRules []string
}
Target names what an edit acts on, durably enough to find it again.
An element target has a Locator (a selector that was unique in the document it was saved from), usually a Fingerprint, and optionally an Anchor. A text or comment target has Kind "text" or "comment", a Parent element target, an Index among the parent's child nodes and a Fingerprint with Text. A rule target has Kind "rule", a Sheet, the rule's Selector (white space collapsed; "@name prelude" for an at-rule), the Selectors of the enclosing rules in AtRules, an Index among rules with the same selector and enclosing rules, and a Fingerprint with Declarations.
type Token ¶
type Token struct {
Kind TokenKind
// Data is the characters of a character token, the data of a comment or
// of a processing instruction. Newlines are normalised and character
// references decoded.
Data string
// Name is the lower-cased name of a tag or doctype, or the target of a
// processing instruction.
Name string
// Attrs lists a tag's attributes in source order. A repeated attribute
// name is dropped: the first wins.
Attrs []TokenAttr
// Duplicates lists the attributes dropped from Attrs as repeats, in
// source order, with their ranges.
Duplicates []TokenAttr
SelfClosing bool
// Doctype fields: the identifiers and the force-quirks flag. The Has
// fields tell a missing name or identifier from an empty one.
PublicID, SystemID string
HasName, HasPublic, HasSystem bool
ForceQuirks bool
// Start and End are the token's byte range in the input. For a character
// token they cover the source characters of the run, a character
// reference's whole text included; for a comment, from "<" to after ">"
// (or the end of input when unclosed).
Start, End int
// NameStart and NameEnd are the byte range of a tag's or doctype's name,
// or a processing instruction's target, as written in the input (before
// lower-casing).
NameStart, NameEnd int
}
Token is one token of the HTML tokenizer.
type TokenAttr ¶
type TokenAttr struct {
// Name is the attribute name, lower-cased.
Name string
// Value is the value with character references decoded.
Value string
// Quote is how the value was written.
Quote AttrQuote
// Start and End bound the whole attribute in the input, from the first
// character of the name to the end of the value (after a closing quote).
// NameStart and NameEnd bound the name as written; ValueStart and
// ValueEnd bound the value as written, inside any quotes and with its
// character references undecoded (both equal End with no value). All are
// byte offsets in the input.
Start, End, NameStart, NameEnd, ValueStart, ValueEnd int
}
TokenAttr is an attribute of a tag token.
type TokenKind ¶
type TokenKind uint8
TokenKind is the kind of a Token.
const ( // EOFToken ends the stream. EOFToken TokenKind = iota // CharacterToken is a run of character data. CharacterToken // StartTagToken is a start tag. StartTagToken // EndTagToken is an end tag. EndTagToken // CommentToken is a comment. CommentToken // DoctypeToken is a document type declaration. DoctypeToken // ProcessingInstructionToken is a processing instruction, "<?target data?>". ProcessingInstructionToken )
The kinds of token.
type Tokenizer ¶
type Tokenizer struct {
// contains filtered or unexported fields
}
Tokenizer runs the HTML tokenizer of the standard alone, without a tree builder. It reads UTF-8 text; a lone surrogate written in the three-byte form UTF-8 would use for it is passed through and reported as a parse error. Use Parse for ordinary work: the tokenizer exists for tools and for testing. A Tokenizer is for one goroutine at a time; the zero Tokenizer and a nil *Tokenizer yield no tokens.
Example (Positions) ¶
package main
import (
"fmt"
"recursiveai.org/go/onehtml"
)
func main() {
src := []byte(`<a href="x" hidden>`)
z := onehtml.NewTokenizer(src)
tok, _ := z.Next()
for _, a := range tok.Attrs {
fmt.Printf("%s %s %q\n", a.Name, a.Quote, src[a.Start:a.End])
}
}
Output: href double "href=\"x\"" hidden none "hidden"
func NewTokenizer ¶
func NewTokenizer(src []byte, opts ...ParseOption) *Tokenizer
NewTokenizer returns a tokenizer over src, starting in DataState. It never copies src; the caller must not modify it while tokenizing. Of the options only WithLimits applies, to the input size (Limits.MaxInputBytes) and the attributes of one tag (Limits.MaxAttributes); exceeding one ends the stream and is reported by Tokenizer.Err.
Example ¶
The tokenizer can run alone.
package main
import (
"fmt"
"recursiveai.org/go/onehtml"
)
func main() {
z := onehtml.NewTokenizer([]byte(`<a href=x>t</a>`))
for {
tk, ok := z.Next()
if !ok {
break
}
fmt.Printf("%v %q %q\n", tk.Kind, tk.Name, tk.Data)
}
}
Output: start-tag "a" "" character "" "t" end-tag "a" "" eof "" ""
func (*Tokenizer) Err ¶
Err returns the *LimitError that ended the stream early, or nil.
func (*Tokenizer) Errors ¶
func (z *Tokenizer) Errors() []ParseError
Errors returns the parse errors found so far, in input order, together with the input stream errors (control characters, noncharacters, surrogates) of the whole input. Offset and TextOffset are both offsets in the input. Read the tokenizer to the end first for a complete list.
func (*Tokenizer) SetForeignContent ¶
SetForeignContent says whether the adjusted current node is outside the HTML namespace, which makes "<![CDATA[" start a section of character data instead of a bogus comment. A tree builder sets it before each token; the default is false.
func (*Tokenizer) SetLastStartTag ¶
SetLastStartTag sets the name of the last start tag emitted, which decides which end tag ends the text states (the "appropriate end tag").
func (*Tokenizer) SetState ¶
func (z *Tokenizer) SetState(s TokenizerState)
SetState sets the state the tokenizer reads in next.
type TokenizerState ¶
type TokenizerState uint8
TokenizerState is an initial state of the Tokenizer.
const ( // DataState is the default state. DataState TokenizerState = iota // RCDATAState is the state for title and textarea content: character // references are decoded but there is no markup but the end tag. RCDATAState // RAWTEXTState is the state for style, xmp, iframe, noembed and noframes // content. RAWTEXTState // ScriptDataState is the state for script content. ScriptDataState // PLAINTEXTState is the state after a plaintext start tag: everything is text. PLAINTEXTState // CDATASectionState is the state inside a CDATA section, which ends at "]]>". CDATASectionState )
The states a tokenizer can start in. They are the states the HTML tree builder switches the tokenizer to for text-only elements.
Source Files
¶
- cascade.go
- cascade_hints.go
- cascade_invalid.go
- cascade_property.go
- cascade_pseudo.go
- cascade_rules.go
- cascade_sheets.go
- cascade_source.go
- changes.go
- changes_ext.go
- doc.go
- dom.go
- dom_read.go
- edit.go
- edit_api.go
- edit_dom.go
- edit_file.go
- errors.go
- font_metrics.go
- foreign.go
- foreign_tables.go
- format.go
- keyframes.go
- keyframes_resolve.go
- locate.go
- markup.go
- modes.go
- parse.go
- parser.go
- quirks_tables.go
- replay.go
- restyle.go
- restyle_sens.go
- rewrite.go
- rewrite_plan.go
- rewrite_report.go
- selcompile.go
- selectedcontent.go
- selector.go
- selform.go
- selhtml.go
- selmatch.go
- selpseudo.go
- selvalid.go
- serialize.go
- sheetedit.go
- sniff.go
- stylesheet.go
- tokenizer.go
- tokenizer_public.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package accessibility computes the accessibility tree a browser exposes to assistive technology, from a parsed onehtml document and its style cascade: roles, accessible names and descriptions, states and properties, and the tree structure with aria-owns.
|
Package accessibility computes the accessibility tree a browser exposes to assistive technology, from a parsed onehtml document and its style cascade: roles, accessible names and descriptions, states and properties, and the tree structure with aria-owns. |
|
aria
Package aria is the WAI-ARIA taxonomy: every role, state and property of WAI-ARIA 1.3 (Editor's Draft), the Digital Publishing module 1.1 and the Graphics module 1.0, with the characteristics the specifications give them: where a role sits in the role hierarchy, which attributes it requires, supports, deprecates or prohibits, where its accessible name may come from, and what values an attribute accepts.
|
Package aria is the WAI-ARIA taxonomy: every role, state and property of WAI-ARIA 1.3 (Editor's Draft), the Digital Publishing module 1.1 and the Graphics module 1.0, with the characteristics the specifications give them: where a role sits in the role hierarchy, which attributes it requires, supports, deprecates or prohibits, where its accessible name may come from, and what values an attribute accepts. |
|
validation
Package validation checks a document against the accessibility rules of every WCAG version and level, plus best practices, and reports labelled results that point at elements.
|
Package validation checks a document against the accessibility rules of every WCAG version and level, plus best practices, and reports labelled results that point at elements. |
|
validation/gen
command
Command gen writes catalogue_gen.go: the WCAG success criteria, the W3C list of ACT rules and the published table of axe-core rules, from the JSON files next to it (see SOURCE.md).
|
Command gen writes catalogue_gen.go: the WCAG success criteria, the W3C list of ACT rules and the published table of axe-core rules, from the JSON files next to it (see SOURCE.md). |
|
Package css is the CSS side of onehtml that does not need a document: the CSS Syntax tokenizer and parser with exact source ranges, canonical serialization, and the conditions of conditional rules (media query lists and @supports).
|
Package css is the CSS side of onehtml that does not need a document: the CSS Syntax tokenizer and parser with exact source ranges, canonical serialization, and the conditions of conditional rules (media query lists and @supports). |
|
Package encoding implements the character encodings of the WHATWG Encoding Standard: finding an encoding by label, decoding bytes to text and encoding text to bytes, one-shot or streaming.
|
Package encoding implements the character encodings of the WHATWG Encoding Standard: finding an encoding by label, decoding bytes to text and encoding text to bytes, one-shot or streaming. |
|
internal
|
|
|
aria
Package aria holds the WAI-ARIA taxonomy: every role, state and property of WAI-ARIA 1.3 (Editor's Draft), Digital Publishing WAI-ARIA 1.1 and WAI-ARIA Graphics 1.0, with the characteristics the specifications give them.
|
Package aria holds the WAI-ARIA taxonomy: every role, state and property of WAI-ARIA 1.3 (Editor's Draft), Digital Publishing WAI-ARIA 1.1 and WAI-ARIA Graphics 1.0, with the characteristics the specifications give them. |
|
aria/gen
command
Command gen writes data_gen.go, the WAI-ARIA role, state and property tables, from the W3C documents in spec/.
|
Command gen writes data_gen.go, the WAI-ARIA role, state and property tables, from the W3C documents in spec/. |
|
atom
Package atom interns the element and attribute names the parser compares against, so that hot paths compare integers rather than strings.
|
Package atom interns the element and attribute names the parser compares against, so that hot paths compare integers rather than strings. |
|
cond
Package cond evaluates the conditions of conditional rules: media queries (Media Queries 4 and 5, with range syntax) and @supports conditions (CSS Conditional 3 and 4).
|
Package cond evaluates the conditions of conditional rules: media queries (Media Queries 4 and 5, with range syntax) and @supports conditions (CSS Conditional 3 and 4). |
|
css
Package css implements CSS Syntax: input decoding for stylesheets that arrive as bytes, the tokenizer, bracket pairing, and the parser entry points (stylesheet, rule, declaration, block contents, component values).
|
Package css implements CSS Syntax: input decoding for stylesheets that arrive as bytes, the tokenizer, bracket pairing, and the parser entry points (stylesheet, rule, declaration, block contents, component values). |
|
encoding
Package encoding implements the character encodings of the WHATWG Encoding Standard that HTML requires: label lookup, byte order mark and <meta> sniffing, and decoders from every encoding to UTF-8.
|
Package encoding implements the character encodings of the WHATWG Encoding Standard that HTML requires: label lookup, byte order mark and <meta> sniffing, and decoders from every encoding to UTF-8. |
|
entities
Package entities holds the named character references of the HTML standard.
|
Package entities holds the named character references of the HTML standard. |
|
langtag
Package langtag answers the two questions the accessibility rules ask about language tags: does the primary subtag name a language in the IANA Language Subtag Registry, and is the tag well formed (RFC 5646 section 2.1).
|
Package langtag answers the two questions the accessibility rules ask about language tags: does the primary subtag name a language in the IANA Language Subtag Registry, and is the tag well formed (RFC 5646 section 2.1). |
|
limit
Package limit holds the one sentinel every public package's limit error matches, so errors.Is(err, onehtml.ErrLimit) answers the same question for a document, a selector, a stylesheet and a decoder.
|
Package limit holds the one sentinel every public package's limit error matches, so errors.Is(err, onehtml.ErrLimit) answers the same question for a document, a selector, a stylesheet and a decoder. |
|
selector
Package selector parses Selectors Level 4 into an AST, computes specificity and serializes selectors as CSSOM defines for selectorText.
|
Package selector parses Selectors Level 4 into an AST, computes specificity and serializes selectors as CSSOM defines for selectorText. |
|
style
Package style is the value half of the CSS cascade: the property table, declarations and shorthand expansion, custom properties with var() substitution, the CSS-wide keywords, typed computed values (lengths, colors, math functions, fonts, display and the other properties the accessibility tree reads) and their CSSOM serialization.
|
Package style is the value half of the CSS cascade: the property table, declarations and shorthand expansion, custom properties with var() substitution, the CSS-wide keywords, typed computed values (lengths, colors, math functions, fonts, display and the other properties the accessibility tree reads) and their CSSOM serialization. |
|
ua
Package ua holds the user agent style sheet of the HTML Standard, section "Rendering", as data.
|
Package ua holds the user agent style sheet of the HTML Standard, section "Rendering", as data. |
|
ua/gen
command
Command gen extracts the style sheet blocks of the HTML Standard's Rendering section into ua_gen.go.
|
Command gen extracts the style sheet blocks of the HTML Standard's Rendering section into ua_gen.go. |
|
whatwgurl
Package whatwgurl resolves URLs the way the WHATWG URL Standard says (https://url.spec.whatwg.org/): the basic URL parser, host parsing and serialisation.
|
Package whatwgurl resolves URLs the way the WHATWG URL Standard says (https://url.spec.whatwg.org/): the basic URL parser, host parsing and serialisation. |