Documentation
¶
Overview ¶
Package htmlcore converts HTML and MD into Cogent Core widget trees.
Index ¶
- Constants
- Variables
- func ExtractText(ctx *Context) string
- func ExtractTextExclude(ctx *Context, excludeSubs ...string) (string, *html.Node)
- func Get(ctx *Context, url string) (*http.Response, error)
- func GetAttr(n *html.Node, attr string) string
- func GetLanguage(class string) string
- func GetURLFromFS(fsys fs.FS, rawURL string) (*http.Response, error)
- func HasAttr(n *html.Node, attr string) bool
- func MDGetAttr(n ast.Node, attr string) string
- func MDSetAttr(n ast.Node, attr, value string)
- func MDToHTML(ctx *Context, md []byte) []byte
- func New[T tree.NodeValue](ctx *Context) *T
- func NodeOf(w core.Widget) *html.Node
- func ParseHTML(ctx *Context, r io.Reader) (*html.Node, error)
- func ParseRelativeURL(rawURL, base string) (*url.URL, error)
- func PseudoElement(n *html.Node) string
- func ReadDocument(ctx *Context, parent core.Widget, n *html.Node) error
- func ReadHTML(ctx *Context, parent core.Widget, r io.Reader) error
- func ReadHTMLString(ctx *Context, parent core.Widget, s string) error
- func ReadMD(ctx *Context, parent core.Widget, b []byte) error
- func ReadMDString(ctx *Context, parent core.Widget, s string) error
- func ScreenMediaWidth() float32
- func SetRequestHeaders(req *http.Request)
- func TagTexts(w core.Widget)
- func TextElement(tx *core.Text) *core.WidgetBase
- func TextTag(tx *core.Text) string
- type Context
- func (c *Context) AddWidgetHandler(f func(w core.Widget))
- func (c *Context) AddWikilinkHandler(h WikilinkHandler)
- func (c *Context) ComputedValue(n *html.Node, prop string) string
- func (c *Context) HasRest() bool
- func (c *Context) HoverAffects(n *html.Node) bool
- func (c *Context) InlineParent() core.Widget
- func (c *Context) LinkButton(bt *core.Button, url string) *core.Button
- func (c *Context) LinkButtonUpdating(bt *core.Button, url func() string) *core.Button
- func (c *Context) MediaChanged(width float32) bool
- func (c *Context) MediaMatches(query string) bool
- func (c *Context) NewPage() *Context
- func (c *Context) Parent() core.Widget
- func (c *Context) ReadRest() (core.Widget, int, error)
- func (c *Context) SetStyleAttr(node *html.Node, style string) error
- type ImageCache
- type WikilinkHandler
Constants ¶
const ModalAttr = "data-htmlcore-modal"
ModalAttr is the attribute of the dialogs that are shown as modal (as by the showModal of scripts), which the :modal selector of CSS selects (and the style of browsers for them, in the top layer).
Variables ¶
var AcceptLanguage = acceptLanguage(firstEnv("LC_ALL", "LC_MESSAGES", "LANG"))
AcceptLanguage is the Accept-Language header of the requests of the default Context.GetURL (see SetRequestHeaders), from the locale of the system (the LC_ALL, LC_MESSAGES, or LANG environment variable) or US English. Some sites send reduced pages to requests without it.
var FontDecoder func(data []byte) ([]byte, error)
FontDecoder, if set, decodes the data of web fonts in formats that the text shapers do not read (as WOFF2) into TrueType or OpenType data, for Context.WebFonts. Fonts that it cannot decode (with an error) are not used.
var UserAgent = "Mozilla/5.0 (" + userAgentPlatform() + ") AppleWebKit/537.36 (KHTML, like Gecko) CogentCore/1.0 Safari/537.36"
UserAgent is the User-Agent header of the requests of the default Context.GetURL (see SetRequestHeaders). It has the form of the user agents of browsers, for the platform that the app runs on, naming Cogent Core: sites treat the "compatible; ...; +url" form of crawlers (and the default of the Go HTTP client) as bots. Scripts should report the same value (navigator.userAgent), since sites check that they match.
Functions ¶
func ExtractText ¶
ExtractText recursively extracts all of the text from the children of the given *html.Node, adding any appropriate inline markup for formatted text. It adds any non-text elements to the given core.Widget using [readHTMLNode]. It should not be called on text nodes themselves; for that, you can directly access the html.Node.Data field. It uses the given page URL for context when resolving URLs, but it can be omitted if not available.
func ExtractTextExclude ¶ added in v0.3.12
ExtractTextExclude recursively extracts all of the text from the children of the given *html.Node, adding any appropriate inline markup for formatted text. It adds any non-text elements to the given core.Widget using [readHTMLNode], except those types listed in the excludeSubs list. If one of those types is encountered, it is returned.
func GetAttr ¶
GetAttr gets the given attribute from the given node, returning "" if the attribute is not found.
func GetLanguage ¶ added in v0.3.13
GetLanguage returns the 'x' in a `language-x` class from the given string of class(es).
func GetURLFromFS ¶ added in v0.3.8
GetURLFromFS can be used for Context.GetURL to get resources from the given file system.
func MDGetAttr ¶ added in v0.3.11
MDGetAttr gets the given attribute from the given markdown node, returning "" if the attribute is not found.
func New ¶
New adds a new widget of the given type to the context parent. It automatically calls [Context.config] on the resulting widget.
func NodeOf ¶ added in v0.5.28
NodeOf returns the HTML node of the element that the given widget is for, or that of the nearest widget that it is in that has one (as for the text of an element), or nil if there is none. The nodes are those of the document that was read (see ReadDocument).
func ParseHTML ¶ added in v0.5.28
ParseHTML parses the given HTML as browsers do: with scripting enabled if Context.Scripting is set (so that the content of noscript elements is their text, which is not shown), and otherwise as browsers do without JavaScript, so that the content of noscript elements is shown.
func ParseRelativeURL ¶
ParseRelativeURL parses the given raw URL relative to the given base URL.
func PseudoElement ¶ added in v0.5.28
PseudoElement returns the kind of the pseudo-element ("before" or "after") whose box the given element is (an element that is not in the document; see the widgets of NodeOf), or "" if it is not one, as for an app that gives the elements of the document events: the clicks on a pseudo-element are those of its element (as the chevrons of the sidebar of MDN).
func ReadDocument ¶ added in v0.5.28
ReadDocument adds the Cogent Core widgets for the given parsed HTML document (or other node, with its next siblings) to the given widget, using the given context, as ReadHTML does after it parses its HTML. It allows the document to be read again after it is changed, as by the scripts of a page (which need its nodes), with a new context for each read (see Context.NewPage); the nodes of the document are those of the widgets (see NodeOf).
func ReadHTML ¶
ReadHTML reads HTML from the given io.Reader and adds corresponding Cogent Core widgets to the given core.Widget, using the given context.
func ReadHTMLString ¶
ReadHTMLString reads HTML from the given string and adds corresponding Cogent Core widgets to the given core.Widget, using the given context.
func ReadMD ¶
ReadMD reads MD (markdown) from the given bytes and adds corresponding Cogent Core widgets to the given core.Widget, using the given context.
func ReadMDString ¶
ReadMDString reads MD (markdown) from the given string and adds corresponding Cogent Core widgets to the given core.Widget, using the given context.
func ScreenMediaWidth ¶ added in v0.5.24
func ScreenMediaWidth() float32
ScreenMediaWidth returns the width of the screen in CSS px (dp), for the @media rules of style sheets when Context.MediaWidth is not set, or 1024 if there is no screen. An app that reads HTML in another goroutine should set MediaWidth (as to this) in its main goroutine first, as the screens can change in it (as when a window is made).
func SetRequestHeaders ¶ added in v0.5.28
SetRequestHeaders sets the headers of the given request that browsers send: the UserAgent, AcceptLanguage, and Accept. (Accept-Encoding is set by the Go HTTP client, which decompresses the gzip responses.)
func TagTexts ¶ added in v0.5.24
TagTexts gives each text in the given widget the "tag" and "id" properties of the HTML element that it is the text of (see TextElement), if it does not have its own, as for printing it apart from the widget of its element (as in a PDF, which styles headings by their tags, and links to their ids).
func TextElement ¶ added in v0.5.24
func TextElement(tx *core.Text) *core.WidgetBase
TextElement returns the widget of the HTML element that the given text is the text of: the text itself if it has a "tag" property, or else the widget with a tag that it is in (possibly in an inline container of it), as the text of a paragraph or heading is in the frame of its element.
Types ¶
type Context ¶
type Context struct {
// Node is the node that is currently being read.
Node *html.Node
// RefreshURL is the URL of the first meta element with an http-equiv
// of refresh in the HTML read, if any, which an app that shows web pages
// can open next, as browsers do (as for a page that redirects browsers
// without JavaScript to another one). It must be reset before each read.
RefreshURL string
// Style is CSS that is added to the style sheets of each page that is
// read, before those of the page (as a user
// style sheet of a browser), as for the margins of an app's pages.
Style string
// Title is the text of the first title element in the HTML read,
// if any, as for the title of a window or tab that shows the page.
Title string
// MediaWidth, if positive, is the width of the viewport in CSS px (dp)
// that the @media rules of style sheets are for; otherwise, it is the
// width of the screen.
MediaWidth float32
// MediaHeight, if positive, is the height of the viewport in CSS px (dp)
// that vh lengths are relative to; otherwise, they are relative to the
// height of the scene.
MediaHeight float32
// Zoom, if positive, is the zoom factor of the page, as in browsers:
// all of its sizes are multiplied by it (see
// [styles.Style.Zoom]). MediaWidth and MediaHeight are then the size of
// the viewport divided by it, as its CSS px are larger (or smaller).
Zoom float32
// WebFonts is whether the web fonts of the @font-face rules of the
// style sheets of pages are loaded (once for each URL, for all pages),
// and used for the font families that they are for (see
// [fonts.AddWebFont]). Fonts in the WOFF2 format need a [FontDecoder].
WebFonts bool
// Scripting is whether the scripts of the pages are run (by the app
// that reads them, as htmlcore does not run them): the HTML is then
// parsed with scripting enabled (see [ParseHTML]), and noscript
// elements are not displayed, as in browsers with JavaScript.
Scripting bool
// Checked, if set, returns whether the given checkbox or radio input
// element is checked, for the :checked selector of CSS, as for a control
// that the user or a script has checked (as the CSS menus of Wikipedia,
// which show when their hidden checkbox is checked). By default, it is
// the checked attribute (the initial state).
Checked func(n *html.Node) bool
// Unrendered, if set, returns whether the given element is not rendered
// for a reason outside of its styles, as a child of an element with a
// shadow root (made by a script) that it is not assigned to a slot of,
// as the closed dropdown panels of the menus of MDN, which its shadow
// root shows (in a slot) only when they are open.
Unrendered func(n *html.Node) bool
// ToggleDetails, if set, toggles the given details element open or
// closed in the document that the page is read from (its open
// attribute), on a click of its summary, as for an app that runs
// scripts, which reads the page again then: its [open] selectors
// apply (as the rotated chevrons of the sidebar of MDN), and it stays
// open when the page is read again. It returns whether it toggled them:
// otherwise (or if it is not set), the details of the page that is read
// are shown or hidden in place (as when the scripts were stopped).
ToggleDetails func(n *html.Node) bool
// Hovered, if set, returns whether the mouse is over the given element
// (in it, or in an element in it), for the :hover selectors of CSS (as
// the submenus of pkg.go.dev, shown on the :hover of their menu items),
// as for an app that reads the page again when that changes for the
// elements for which [Context.HoverAffects] is true. Otherwise, :hover
// selects nothing.
Hovered func(n *html.Node) bool
// NewParent is the current parent widget that children of
// the previously read element should be added to, if any.
NewParent core.Widget
// BlockParent is the current parent widget that non-inline elements
// should be added to.
BlockParent core.Widget
// TableParent is the current table being generated.
TableParent *core.Frame
// PageURL, if not "", is the URL of the current page.
// Otherwise, there is no current page.
PageURL string
// OpenURL is the function used to open URLs,
// which defaults to [system.App.OpenURL].
OpenURL func(url string, e events.Event)
// OpenLink, if set, is used in place of OpenURL for the clicks on the
// frames of links (and the widgets in them), with the link element
// (as for a page with scripts, which get the click of the element
// that is clicked, not of another link to the same URL).
OpenLink func(link *html.Node, url string, e events.Event)
// GetURL is the function used to get resources from URLs,
// which defaults to [http.Get].
GetURL func(url string) (*http.Response, error)
// PostURL, if not nil, is the function used to open URLs with a POST
// request with the given body of the given content type, as for
// submitting forms with the POST method. If it is nil, those forms
// can not be submitted.
PostURL func(url, contentType string, body []byte, e events.Event)
// ElementHandlers is a map of handler functions for each HTML element
// type (eg: "button", "input", "p"). It is empty by default, but can be
// used by anyone in need of behavior different than the default behavior
// defined in [handleElement] (for example, for custom elements).
// If the handler for an element returns false, then the default behavior
// for an element is used.
ElementHandlers map[string]func(ctx *Context) bool
// WikilinkHandlers is a list of handlers to use for wikilinks.
// If one returns "", "", the next ones will be tried instead.
// The functions are tried in sequential ascending order.
// See [Context.AddWikilinkHandler] to add a new handler.
WikilinkHandlers []WikilinkHandler
// AttributeHandlers is a map of markdown render handler functions
// for custom attribute values that are specified in {tag: value}
// attributes prior to markdown elements in the markdown source.
// The map key is the tag in the attribute, which is then passed
// to the function, along with the markdown node being rendered.
// Alternative or additional HTML output can be written to the given writer.
// If the handler function returns true, then the default HTML code
// will not be generated.
AttributeHandlers map[string]func(ctx *Context, w io.Writer, node ast.Node, entering bool, tag, value string) bool
// WidgetHandlers is a list of handler functions for each Widget,
// called in sequential order for each widget that is created,
// after it has been configured by the existing handlers etc.
// This allows for additional styling to be applied based on the
// type of widget, for example.
WidgetHandlers []func(w core.Widget)
// DelayedImageLoad causes images to be loaded at a delay.
// if not set, then they are loaded immediately.
DelayedImageLoad bool
// ImageCache, if non-nil, caches the decoded images of img elements
// by their resolved URL, so that rebuilding a page does not decode
// them again. It must only be set when [Context.GetURL] returns the
// same content for the same URL until the cache is reset. It is nil
// by default; see [NewImageCache].
ImageCache *ImageCache
// StageSize, if positive, is the size of the content of the body (in
// runes of text, with estimates for other elements) after which
// [ReadHTML] stops adding the widgets of its top-level elements,
// leaving the rest for [Context.ReadRest]. This allows the first part
// of a long page to be shown sooner.
StageSize int
// contains filtered or unexported fields
}
Context contains context information about the current state of a htmlcore reader and its surrounding context. It should be created with NewContext.
func (*Context) AddWidgetHandler ¶ added in v0.3.13
AddWidgetHandler adds given widget handler function
func (*Context) AddWikilinkHandler ¶ added in v0.3.8
func (c *Context) AddWikilinkHandler(h WikilinkHandler)
AddWikilinkHandler adds a new WikilinkHandler to Context.WikilinkHandlers. If it returns "", "", the next handlers will be tried instead. The functions are tried in sequential ascending order.
func (*Context) ComputedValue ¶ added in v0.5.28
ComputedValue returns the value of the given CSS property for the given element, as cascaded by the style sheets of the page that it was read with (with var() resolved): that of the declaration of the element that applies, or, for an inherited property (or one that is inherit), that of its nearest ancestor with one, or "" if there is none (as for the initial value). It is for the computed styles of scripts, which can convert its values (as colors and relative lengths) as they need.
func (*Context) HasRest ¶ added in v0.5.0
HasRest returns whether ReadHTML has left elements to read with Context.ReadRest (see Context.StageSize).
func (*Context) HoverAffects ¶ added in v0.5.28
HoverAffects returns whether the hover of the given element changes the styles of other elements, by the :hover selectors of the style sheets of the page that was read (as the menu items of pkg.go.dev, whose submenus are shown on their hover), for which an app that sets Context.Hovered reads the page again when the hover of the element changes.
func (*Context) InlineParent ¶
InlineParent returns the current parent widget that inline elements should be added to.
func (*Context) LinkButton ¶ added in v0.3.8
LinkButton is a helper function that makes the given button open the given link when clicked on, using Context.OpenURL. The advantage of using this is that it does tree.NodeBase.SetProperty of "href" to the given url, allowing generatehtml to create an <a> element for HTML preview and SEO purposes. It also sets the tooltip to the URL.
See also Context.LinkButtonUpdating for a dynamic version.
func (*Context) LinkButtonUpdating ¶ added in v0.3.9
LinkButtonUpdating is a version of Context.LinkButton that is robust to a changing/dynamic URL, using an Updater and a URL function instead of a variable.
func (*Context) MediaChanged ¶ added in v0.5.26
MediaChanged returns whether the HTML read with the context would be read differently for a viewport of the given width in CSS px (dp): whether a media query of its style sheets (as of an @media rule) or a number of columns estimated from the width (for column-width) has another result for it. An app that shows pages in a viewport whose width can change, as when its window is resized, can then read the page again with a new context (see Context.NewPage) with that Context.MediaWidth, as browsers apply the rules of the new width. It must be called in the goroutine that styles the widgets of the page, once the page has been read.
func (*Context) MediaMatches ¶ added in v0.5.28
MediaMatches returns whether the given media query list (as of an @media rule) matches the viewport of the context, as for matchMedia in the scripts of a page.
func (*Context) NewPage ¶ added in v0.5.24
NewPage returns a new context for reading a new page, with the settings of this context (as for media, styles, URLs, and handlers), but none of the state from reading a page (as its style sheets). A context that is used to read pages one after another (as in a browser) should get a new one for each page with this, so that nothing of one page affects the next.
func (*Context) Parent ¶
Parent returns the current parent widget that a widget associated with the current node should be added to. It may make changes to the widget tree, so the widget must be added to the resulting parent immediately.
func (*Context) ReadRest ¶ added in v0.5.0
ReadRest adds the widgets of the elements that ReadHTML left (see Context.StageSize), and returns the widget that they are added to and the index of the first child added, which need to be updated. The context must not have been used to read other HTML since.
type ImageCache ¶ added in v0.5.0
type ImageCache struct {
// MaxBytes is the maximum total size of the cached images, in bytes
// of decoded pixels. The least recently used images are removed
// to keep the total size within it, and an image larger than it
// is not cached.
MaxBytes int
// contains filtered or unexported fields
}
ImageCache is a cache of decoded images, keyed by their resolved URL, so that rebuilding a page does not decode the same images again. It keeps the most recently used images up to a total size in bytes, and it is safe for concurrent use.
The cached images are shared by all of the widgets that show them, so they must not be modified. Images are only read when they are rendered: core.Image and the resizing and cropping functions of imagex make new images.
func NewImageCache ¶ added in v0.5.0
func NewImageCache(maxBytes int) *ImageCache
NewImageCache returns a new ImageCache that keeps images up to the given total size in bytes.
func (*ImageCache) Add ¶ added in v0.5.0
func (ic *ImageCache) Add(url string, img image.Image)
Add adds the given image for the given resolved URL to the cache, removing the least recently used images as needed to stay within ImageCache.MaxBytes.
func (*ImageCache) Get ¶ added in v0.5.0
func (ic *ImageCache) Get(url string) image.Image
Get returns the cached image for the given resolved URL, or nil.
func (*ImageCache) Reset ¶ added in v0.5.0
func (ic *ImageCache) Reset()
Reset removes all of the images from the cache.
type WikilinkHandler ¶ added in v0.3.8
WikilinkHandler is a function that converts wikilink text to a corresponding URL and label text. If it returns "", "", the handler will be skipped in favor of the next possible handlers. Wikilinks are of the form [[wikilink text]]. Only the text inside of the brackets is passed to the handler. If there is additional text directly after the closing brackets without spaces or punctuation, it will be appended to the label text after the handler is run (ex: [[widget]]s).
func GoDocWikilink ¶ added in v0.3.8
func GoDocWikilink(prefix string, pkg string) WikilinkHandler
GoDocWikilink returns a WikilinkHandler that converts wikilinks of the form [[prefix:identifier]] to a pkg.go.dev URL starting at pkg. For example, with prefix="doc" and pkg="cogentcore.org/core", the wikilink [[doc:core.Button]] will result in the URL "https://pkg.go.dev/cogentcore.org/core/core#Button".
Source Files
¶
- cascade.go
- color.go
- columns.go
- container.go
- context.go
- details.go
- element.go
- filter.go
- font.go
- forms.go
- grid.go
- handler.go
- hints.go
- html.go
- ico.go
- image.go
- imagecache.go
- inline.go
- length.go
- list.go
- margins.go
- mask.go
- md.go
- media.go
- properties.go
- pseudo.go
- resolve.go
- srcset.go
- styler.go
- table.go
- text.go
- url.go
- webfont.go
- wikilink.go
Directories
¶
| Path | Synopsis |
|---|---|
|
examples
|
|
|
html
command
|
|
|
md
command
|
|
|
Package tohtml converts Cogent Core widgets to HTML, which the core tool uses to pre-render apps for a preview while the app loads and for SEO purposes.
|
Package tohtml converts Cogent Core widgets to HTML, which the core tool uses to pre-render apps for a preview while the app loads and for SEO purposes. |