Documentation
¶
Overview ¶
Package htmlengine is the engine that reads HTML and Markdown into Cogent Core widget trees: parsing documents, the CSS cascade and the browser styles of elements, making and laying out the widgets of the elements, and reading and restyling the changed elements of documents (as by the scripts of pages) in place. Package htmlcore is the API of it for apps and content sites; apps that show whole web pages, as a browser does, use it directly.
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 StyleSheetURLs(sheet, base string, webFonts bool) []string
- func TagTexts(w core.Widget)
- func TextElement(tx *core.Text) *core.WidgetBase
- func TextTag(tx *core.Text) string
- func VideoSourceOf(w core.Widget) 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) Fallback() string
- func (c *Context) HasRest() bool
- func (c *Context) HoverAffects(n *html.Node) bool
- func (c *Context) InlineParent() core.Widget
- func (c *Context) KeepContainerSizes(prev *Context)
- 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) LockStyles()
- 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) PrefetchURLs(doc *html.Node) []string
- func (c *Context) PrepareReread(self, children []*html.Node) func()
- func (c *Context) PrepareRestyle(changed []*html.Node) func()
- func (c *Context) ReadRest() (core.Widget, int, error)
- func (c *Context) Reread(self, children []*html.Node) bool
- func (c *Context) Restyle(changed []*html.Node) bool
- func (c *Context) ReuseStyles(prev *Context)
- func (c *Context) Reused() string
- func (c *Context) SetStyleAttr(node *html.Node, style string) error
- func (c *Context) UnlockStyles()
- func (c *Context) VideoSource(n *html.Node) string
- func (c *Context) ViewportHeightUsed() bool
- type ImageCache
- func (ic *ImageCache) Add(url string, img image.Image)
- func (ic *ImageCache) AddFailed(url string)
- func (ic *ImageCache) Decode(url string, data []byte)
- func (ic *ImageCache) Failed(url string) bool
- func (ic *ImageCache) Get(url string) image.Image
- func (ic *ImageCache) NewRead()
- func (ic *ImageCache) Reset()
- type Markdown
- type VideoBox
- type WikilinkHandler
Constants ¶
const ( IframeDefaultWidth = 300 IframeDefaultHeight = 150 )
IframeDefaultWidth and IframeDefaultHeight are the size in CSS pixels of an iframe without a width or height, as in browsers.
const ( VideoDefaultWidth = 300 VideoDefaultHeight = 150 )
VideoDefaultWidth and VideoDefaultHeight are the size in CSS pixels of a video element without a width or height, before its size is known, as in browsers.
const ( AudioDefaultWidth = 300 AudioDefaultHeight = 54 )
An audio element (see handleAudio) is displayed only with controls (as the bar of a player), as a box of AudioDefaultWidth by AudioDefaultHeight CSS pixels unless its CSS sets its size, as in Chrome. It is the box of a video element (in which an app plays its audio, with its "video-src"), with the "audio" property: on desktop platforms, a VideoBox with VideoBox.Audio, without an image. Audio elements that are not displayed (without controls, as those that the scripts of pages make) are played by an app too, as from its scripts.
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 is, if set, a function that 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 ¶
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 ¶
GetLanguage returns the 'x' in a `language-x` class from the given string of class(es).
func GetURLFromFS ¶
GetURLFromFS can be used for Context.GetURL to get resources from the given file system.
func MDGetAttr ¶
MDGetAttr gets the given attribute from the given markdown node, returning "" if the attribute is not found.
func MDToHTML ¶
MDToHTML converts the given markdown to HTML, using the given context for wikilinks and attribute handlers.
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 StyleSheetURLs ¶
StyleSheetURLs returns the absolute URLs of the resources that the given style sheet, at the given URL (or in the page at it), gets as it is added to a page: the style sheets that it imports, and the web fonts of its @font-face rules (as [Context.addFontFace] chooses them), if webFonts and they have not been loaded yet. Its media and supports conditions are not checked.
func TagTexts ¶
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 ¶
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.
func TextTag ¶
TextTag returns the name of the HTML element that the given text is the text of (see TextElement), such as "h2" for the text of a heading, or "" if there is none.
func VideoSourceOf ¶
VideoSourceOf returns the URL of the video of the given widget, if it is the image of a video element (see Context.VideoSource), or "".
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 (and percentage heights of the viewport) are
// relative to; otherwise, they are relative to the height of the scene.
// Whether the page used it is [Context.ViewportHeightUsed].
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
// ShadowScope, if set, returns the host of the shadow root whose tree
// the given node is in, or nil if it is in the document, for a page that
// is read as its composed tree, with the content of the shadow roots of
// elements in their place (see shadow.go). The rules of the style sheets
// of a shadow tree apply only to it, and those of the document not to it.
ShadowScope func(n *html.Node) *html.Node
// ComposedParent, if set, returns the parent of the given node in the
// composed tree of the page (see ShadowScope), as it was read, which is
// not its parent in the document for the content of shadow roots and
// the nodes in slots.
ComposedParent func(n *html.Node) *html.Node
// 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
// OnTransition, if set, is called with the transitions of the
// properties of elements that a restyle (as for a change of a class by
// a script) starts, for the app to dispatch their transitionend events
// when they end (as Google sign-in waits for, to show its next step).
OnTransition func(ts []css.Transition)
// 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
// AsyncImages, if set, is how the images of the noscripts of lazy
// images (see Context.noscriptImage) are set as they are gotten in the
// background: it calls the given function, which sets them, with the
// lock of the widgets of the page held (or not, if the page is gone).
// If it is nil, they are gotten as the page is read.
AsyncImages func(f func())
// 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 ¶
AddWidgetHandler adds given widget handler function
func (*Context) AddWikilinkHandler ¶
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 ¶
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) Fallback ¶
Fallback returns why the last Context.Reread or Context.Restyle could not make its changes, for the page to be read again whole (as for the verbose console of an app), or "" if it could.
func (*Context) HasRest ¶
HasRest returns whether ReadHTML has left elements to read with Context.ReadRest (see Context.StageSize).
func (*Context) HoverAffects ¶
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) KeepContainerSizes ¶
KeepContainerSizes sets the containers of the page that the context reads, which is the document that the given context read, read again (as after its scripts change it), to start with the sizes that they had in its last layout, so that the elements in them are styled for those first, not for the viewport until they are laid out (as the panels of repositories of github.com, of font-size: 1cqw, which were shown at the size of the viewport each time that the page was read again). It can be called as the given context's page is laid out.
func (*Context) LinkButton ¶
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 ¶
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) LockStyles ¶
func (c *Context) LockStyles()
LockStyles locks the styles of the elements of the context (see Context.PrepareReread), as for reading them without the lock of the widgets of the page, as the stylers of its widgets do (see core.StyleLockProperty); they must not be locked while the lock of the widgets is taken.
func (*Context) MediaChanged ¶
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 ¶
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 ¶
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) PrefetchURLs ¶
PrefetchURLs returns the absolute URLs of the resources that reading the given document with the context gets, as Context.GetURL gets them: its style sheets (and those that they import, and their web fonts, if they are inline; see StyleSheetURLs for those of the others), its scripts (if Context.Scripting), and its images (as chosen from their srcsets for the width of the context), in that order. It does not change the context.
func (*Context) PrepareReread ¶
PrepareReread reads the given elements again as Context.Reread does, into new widgets, with the styles of the context locked (see Context.LockStyles), and without the lock of the widgets of the page (as it takes time: as long as a second, on nytimes.com, in which the app did not respond), and returns the function that puts the new widgets in the page, with the lock of the widgets held, or nil if they can not be read again (see Context.Fallback).
func (*Context) PrepareRestyle ¶
PrepareRestyle finds the declarations of the given changed elements as Context.Restyle does, with the styles of the context locked (see Context.LockStyles), and without the lock of the widgets of the page (as it takes time), and returns the function that styles the widgets again, with the lock of the widgets held, or nil if they can not be (see Context.Fallback).
func (*Context) ReadRest ¶
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.
func (*Context) Reread ¶
Reread updates the widgets of the page that the context has read for changes of its document, as scripts make, without reading all of it again (which makes new widgets for all of it): self has the elements that have changed themselves (as their attributes), and children those whose children have changed (as nodes added to them, or the text of their text nodes). The nearest element of each that has a frame of its own, whose widgets can be made alone (as one that is not a cell of a table or an item of a grid), is read again, into new widgets, which are reconciled with the old ones with tree.Plan: the widgets of the elements that have not changed, nor those in them, are kept, as are the frames of the elements that have not changed themselves, whose children are reconciled in turn, and the others are replaced. The declarations of the elements are found again as for Context.Restyle, and the widgets of those that are not read again are styled again. It returns false, leaving the page as it was, if the changes can not be made so, for the page to be read again: for a new style sheet, a change of the html element itself, or more elements to read than [Context.rereadLimit].
func (*Context) Restyle ¶
Restyle updates the styles of the widgets of the page that the context has read for the given elements, whose attributes that select them in style rules (as their class and style) or states (as their :hover) have changed, as for the changes that scripts make to the styles of a page, without reading it again (which makes new widgets for all of it). The declarations of the elements, those in them and those after them are found again from the style rules of the page, and the widgets of those whose declarations change are styled again, laid out again if they may have another size. It returns false, leaving the styles as they were, if a change can not be made so, for the page to be read again: one of a property that changes the widgets that elements have (as display, or the content of a pseudo-element) or how they are arranged (as in a grid or a table), or one of an element that has no widget of its own (as an inline element in a run of text).
func (*Context) ReuseStyles ¶
ReuseStyles makes the context, which is to read a document that the given context has read (as the page that the scripts of a page change is read again whole when its changes can not be made otherwise), match the style rules of the document only against the elements whose matches may have changed since: those that have changed (as their attributes), moved, or been added, and those that their changes may change the matches of. The others have the declarations of the rules that matched them in the given context, as long as its rules are the same (as without a new style sheet, or another width of the viewport for its media queries); otherwise all of the rules are matched. Matching the rules is most of the time of reading a page (as about a second for each of the many times that npr.org was read again as it loaded).
func (*Context) Reused ¶
Reused returns how the declarations of the elements were found when the context read its page (see Context.ReuseStyles), for the verbose console: "" if they were all matched as usual.
func (*Context) SetStyleAttr ¶
SetStyleAttr adds the declarations of the given style attribute string to the styles of the current node.
func (*Context) UnlockStyles ¶
func (c *Context) UnlockStyles()
UnlockStyles unlocks the styles of the elements (see Context.LockStyles).
func (*Context) VideoSource ¶
VideoSource returns the absolute URL of the video of the given video element (or of the audio of an audio element): its src, or else the src of its first source element with one, or "" for none.
func (*Context) ViewportHeightUsed ¶
ViewportHeightUsed returns whether the page that the context has read used the height of the viewport (Context.MediaHeight): in vh lengths, percentage heights of the viewport (as html and body of height: 100%), or media queries of height, so that it is read again for another height of its viewport (as the footer of google.com, which was below the bottom of the viewport, as it was as high as the window).
type ImageCache ¶
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 images of the current read of a page (see ImageCache.NewRead) are not removed for others: when they do not all fit, the rest are not cached, so that the next read finds most of them, not none (a plain LRU, read in the same order each time, removes each image before the next read gets to it, as the photos of nytimes.com, which were decoded again in each of the reads of the page that its scripts make, in 4-7s). The URLs of images that could not be gotten or decoded are kept too, so that they are not tried again.
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 ¶
func NewImageCache(maxBytes int) *ImageCache
NewImageCache returns a new ImageCache that keeps images up to the given total size in bytes.
func (*ImageCache) Add ¶
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) AddFailed ¶
func (ic *ImageCache) AddFailed(url string)
AddFailed records that the image of the given resolved URL could not be gotten or decoded, so that it is not tried again.
func (*ImageCache) Decode ¶
func (ic *ImageCache) Decode(url string, data []byte)
Decode decodes the given data of the image at the given (absolute) URL and adds it to the cache, or records that it failed, unless it is cached or being decoded already, as for the images of a page that are gotten before it is read, in parallel (as browsers do), so that reading the page, which decodes its images one at a time, finds them decoded (the large photos of bbc.com took most of the 2s of its first read). A page that reads it meanwhile waits for it (see [ImageCache.waitDecoding]). SVG images are not decoded (they are rendered as they are read).
func (*ImageCache) Failed ¶
func (ic *ImageCache) Failed(url string) bool
Failed returns whether the image of the given resolved URL could not be gotten or decoded before (see ImageCache.AddFailed).
func (*ImageCache) Get ¶
func (ic *ImageCache) Get(url string) image.Image
Get returns the cached image for the given resolved URL, or nil.
func (*ImageCache) NewRead ¶
func (ic *ImageCache) NewRead()
NewRead starts a new read of a page, whose images are then kept over those of the reads before it (see ImageCache).
func (*ImageCache) Reset ¶
func (ic *ImageCache) Reset()
Reset removes all of the images from the cache.
type Markdown ¶
Markdown is a goldmark markdown parser and HTML renderer.
func NewMarkdown ¶
NewMarkdown returns a goldmark converter with the extensions used for Cogent Core content: GitHub flavored markdown, heading ids, raw HTML, block attributes in a {...} line before a block, links opening in a new tab, and, if ctx is non-nil, wikilinks and its AttributeHandlers.
type VideoBox ¶
type VideoBox struct {
core.Frame
// Image shows the poster of the video, and its frames (nil for Audio).
Image *core.Image
// Audio is whether it is the box of an audio element with controls,
// a bar (see handleAudio).
Audio bool
}
VideoBox is the box of a video element on desktop platforms (see video.go), of the size of its video (see [resolver.videoSize]), with an core.Image in it (VideoBox.Image) that shows its poster, and the frames of the video, which an app that plays videos shows in it. The app can add controls over it (as video.Controls), for which the box is positioned (relative), and is rendered as a whole when they change (VideoBox.RenderGroup), as they are partly transparent over the image.
func (*VideoBox) RenderGroup ¶
RenderGroup returns true: the box is rendered as a whole when any widget in it needs to be rendered (see VideoBox).
func (*VideoBox) SetVideoSize ¶
SetVideoSize sets the size of the video, which is the size of the box, or of its aspect when only its width or its height is set by its CSS (as the size of a video once it is opened, which updates the box).
type WikilinkHandler ¶
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 ¶
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
¶
- ancestors.go
- cascade.go
- columns.go
- container.go
- context.go
- details.go
- element.go
- font.go
- forms.go
- grid.go
- handler.go
- hints.go
- html.go
- ico.go
- iframe.go
- image.go
- imagecache.go
- imageswap.go
- inline.go
- list.go
- margins.go
- mask.go
- md.go
- mdmath.go
- media.go
- prefetch.go
- properties.go
- pseudo.go
- reread.go
- resolve.go
- restyle.go
- reuse.go
- shadow.go
- srcset.go
- styler.go
- table.go
- text.go
- url.go
- video.go
- video_notjs.go
- webfont.go
- wikilink.go