Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Markdown, HTML and the web

A Markdown note and an HTML page render as ordinary widgets under the ordinary cascade, and a web page is a window the desktop's own engine draws where the window system allows one.

By the end of this chapter you can show a document that follows a property, answer its links and task boxes, let a reader select and copy from it, and decide whether a real web page can be offered on the machine you are on.

The two views are in the goldberry-html module. Add it beside the toolkit and add its stylesheets beside the controls’ own, or a document renders as unstyled words:

var sheets = new ArrayList<>(Controls.stylesheets(theme));
sheets.add(MarkdownStyles.stylesheet());
sheets.add(HtmlStyles.stylesheet());

Nothing in the core knows the module exists. Its catalogue announces the two node names, and the inflater finds them when the module is on the module path.

The showcase's Markdown screen: a text area on the left holding Markdown source and the rendered document on the right, with headings, emphasis, a list, a task list and a tableThe showcase's Markdown screen: a text area on the left holding Markdown source and the rendered document on the right, with headings, emphasis, a list, a task list and a table

The showcase's Markdown screen. The editor writes one property and the view reads it.

markdown-view

A rendered Markdown document: GitHub’s dialect by default, folded into column, row and text.

A split pane: Markdown source in a monospace text area on the left and the rendered document on the right, with a heading, a paragraph and a task listA split pane: Markdown source in a monospace text area on the left and the rendered document on the right, with a heading, a paragraph and a task list

The source and the document it renders, side by side.

split-pane position=0.5 first-min=240 second-min=240 {
    text-area class="mono" bind="note.source" change="note.set-source" fill=#true
    scroll {
        markdown-view bind="note.source" link="app.open" wikilink="app.open-page" images="app.assets" task="note.toggle-task"
    }
}
import dev.goldberry.markdown.Markdown;
import dev.goldberry.markdown.view.MarkdownView;

var view = MarkdownView.following(model.source())
        .onLink(app::open)
        .onWikiLink(app::openPage)
        .images(assets)
        .onTask(index -> model.setSource(Markdown.toggleTask(model.source(), index)));

A live preview is a binding. The editor writes note.source through its action and the view reads the same property with bind=. Nothing watches the editor or schedules a render: a keystroke marks the view for rebuild and the next frame is the parsed document. A block whose source did not change keeps the widget it had, so a keystroke on a 50 kB note costs about 2 ms of build.

Markup may also carry the document as the node’s argument. syntax picks the dialect, and a view with a document and a binding shows the document until the property answers.

markdown-view "A *little* document." syntax="commonmark"

In Java a Document is a value: Markdown.parse(text) or Markdown.parse(text, MarkdownSyntax.commonMark()) returns a sealed tree an application can walk for an outline before handing it to MarkdownView.of(document). MarkdownView.of(text) parses for the caller who wants a preview and nothing else. MarkdownHtml.of(document) writes the same tree out as an HTML fragment, so a preview and the bytes a server hands out cannot drift.

A rendered document is read, and the application answers. A link is a button.link, a Tab stop that hands its href to link= and does nothing else: no browser opens and no path resolves. A [[wiki link]] hands its target to wikilink=, and a view with no handler draws it inert. An image is its alt text until an ImageSource the application supplies turns the src into pixels. A task box reports its ordinal to task=, and Markdown.toggleTask(source, index) flips that one character of the source. The ordinal crosses as the string a document would have written.

Selection

Drag across the document, double-click a word, triple-click a block, Ctrl+A and Ctrl+C. What lands on the clipboard has the space between words and the newline between blocks that the document implies. Nothing to switch on. A drag repaints rather than rebuilds.

Attributes

AttributeTypeDefaultWhat it does
argumentstring""The Markdown source, shown until bind answers
bindbindingnoneA property whose text is parsed on every build
syntaxgithub, commonmarkgithubThe dialect. Anything else is refused
linkvalued actionnoneHanded a link’s href
wikilinkvalued actionnoneHanded a wiki link’s target
imagesnamed ImageSourcenoneWhere an image’s src becomes pixels
taskvalued actionnoneHanded a task box’s ordinal, from zero
idstringnoneThe view’s id, on the column it builds
classstringnoneClasses on that column

Children are refused, and there is no src= to read a file with.

Styling

markdown-view composes and has no box of its own. It builds a column with the class markdown, and markdown.css hangs every rule off a class: md-h1 to md-h6, md-prose, md-line, md-lines, md-word, md-em, md-strong, md-struck, md-underline, md-code, md-code-block, md-code-line, md-code-language, md-link, md-wikilink, md-list, md-item, md-item-body, md-marker, md-quote, md-quote-body, md-table, md-row, md-cell, md-rule and md-raw. A link is a button with the class link. The sheet is in the toolkit’s base layer, so an application’s rule wins without !important.

Keyboard

Tab reaches each link, and Space or Enter presses it. Ctrl+A selects the document and Ctrl+C copies the selection.

What it does not do

Emphasis uses the italic face. Wrap the view in scroll when the application needs a scrollable viewport.

The showcase's HTML screen: HTML source in a text area on the left and the rendered page on the right, with headings, emphasis, a highlighted phrase and a linkThe showcase's HTML screen: HTML source in a text area on the left and the rendered page on the right, with headings, emphasis, a highlighted phrase and a link

The HTML screen of the showcase: the source and the page it renders.

html-view

A rendered HTML document: parsed in Java into a model of records and folded into the same widgets the Markdown view uses.

A rendered HTML document: a heading, The Red Book, and a paragraph with an italic word and a linkA rendered HTML document: a heading, The Red Book, and a paragraph with an italic word and a link

A heading, emphasis and a link.

scroll {
    html-view bind="doc.source" link="doc.open" images="app.assets"
}
import dev.goldberry.html.Html;
import dev.goldberry.html.view.HtmlView;

var document = Html.parse(help.body());
var view = HtmlView.of(document).onLink(app::navigate).images(assets);
var links = document.find("a");

HtmlView.following(model.source()) is the Java spelling of bind=, and HtmlView.of(text) parses for a caller who wants a page and nothing else. The document may also be the node’s argument:

html-view "<p>A <em>little</em> page with <a href=\"/help\">a link</a>.</p>" link="doc.open"

An anchor becomes a button.link that hands its href to link=. It is a Tab stop, it hovers and it takes Space and Enter, so a help page is navigable from the keyboard. Whether the link may be followed is the application’s: no browser opens, no relative path resolves and nothing is fetched. Selection and copy work as in the Markdown view.

Attributes

AttributeTypeDefaultWhat it does
argumentstring""The HTML source, shown until bind answers
bindbindingnoneA property whose text is parsed on every build
linkvalued actionnoneHanded an anchor’s href
imagesnamed ImageSourcenoneWhere an <img src> becomes pixels. Without one an image is its alt text
author-stylesignored, theme-colours, adapted or as-writtenadaptedWhat is done with the page’s own <style> and style=; see A page’s own styles
idstringnoneThe view’s id, on the column it builds
classstringnoneClasses on that column

Children are refused, and there is no src=.

Styling

html-view builds a column with the class html. Every element contributes the class html-<tag>, so html.css reads like a browser’s default sheet and a tag nobody anticipated is already styleable. A page’s own class="callout" arrives as html-callout. The structural classes are html-block, html-prose, html-line, html-lines, html-word, html-list, html-item, html-item-body, html-marker, html-table, html-row, html-cell, html-caption, html-quote, html-quote-body, html-pre, html-code-line, html-rule and html-term. Headings are html-h1 to html-h6.

A page’s own styles

A page’s <style> blocks and style= attributes are applied to that page and to nothing else in the window, and so are the bgcolor and <font color> of mail written before CSS. A rule a mail writes cannot reach the application round it or the mail beside it.

html-view bind="mail.body" link="mail.open" author-styles="adapted"
HtmlView.following(mail.body()).authorStyles(AuthorStyles.THEME_COLOURS);

What is read is the part that is safe and that the toolkit’s CSS has: colour, the text’s size, weight, style, spacing, alignment, decoration and case, a box’s padding, margin, border, corners and max-width, opacity, visibility, and display: none, which is how a mail hides its preview line. Nothing that fetches is read (url() included), nothing that moves a box out of the page (position, transform, a negative margin), nothing that reads or sets the theme (custom properties and var()), and no font-family, so a mail reads in the application’s own face. @media and every other at-rule are skipped.

Selectors are matched against the page as written, so ul > li, td a and p:first-child mean what they say. :hover, :active and :focus apply as the pointer and the keyboard move. A page’s rules win over the application’s own sheets for the page’s elements; an application that has to insist writes !important.

author-styles= decides what happens to the colours:

ValueWhat the page looks like
adaptedThe default. A background the page paints is kept, and text on it reads: the page’s own colour when it reaches 4.5:1 against that background, dark or light ink when it does not. A text colour with no background of the page’s under it is the theme’s, because it would sit on the theme’s surface
theme-coloursSizes, spacing, boxes and borders as written, every colour the theme’s
as-writtenExactly as written, for a surface the application knows to be white
ignoredThe application’s stylesheets alone, as a help page should be

Inline styles follow the text run. Its background covers the glyph range on each line. Paragraph boxes support padding.

Keyboard

As markdown-view: Tab to each link, Space or Enter to press it, Ctrl+A and Ctrl+C for the selection.

What it does not do

The document view renders a subset of HTML. It delegates links and images to the application. For a page that needs scripts, forms or navigation, use the web view.

Wrapping and hyphenation

Markdown and HTML shape adjacent text of the same style as a run, and lay those runs out in a paragraph. The md-word and html-word classes style the runs. Inline images sit on the baseline. A link can wrap over several lines and stays one Tab stop.

.md-prose, .html-prose { text-align: justify }

Justification expands gaps between words on wrapped lines. The last line and the line before a hard break keep their natural spacing.

For automatic hyphenation, set the language and enable hyphens: auto.

<p lang="en" style="hyphens: auto">An introduction to internationalization.</p>

In Markdown, give markdown-view or an ancestor lang="en" and use .md-prose { hyphens: auto } in the stylesheet. Automatic breaks use bundled American English patterns for English locales with Latin script. A displayed hyphen at a wrap does not change the text copied to the clipboard. A link label with mixed explicit languages uses ordinary wrapping and honours authored soft hyphens.

The default hyphens: manual uses explicit soft hyphens (U+00AD or &shy; in HTML) in any language. Use hyphens: none to suppress them.

The web view

A real web page inside the window, drawn by the desktop’s own engine into a child window placed over the widget’s box. Java only: there is no markup name, because a page is a platform handle a document cannot describe.

import dev.goldberry.widgets.core.web.WebView;
import dev.goldberry.widgets.shell.web.WebPage;

new WebView(WebPage.of("https://goldberry.dev")).withAttributes(Attributes.NONE.id("page"));

A WebPage is a value: WebPage.of(url), WebPage.ofHtml(html) or WebPage.blank(), with title, sized, debug for the engine’s inspector, and on(name, callback) for a function the page’s own script can call. The widget follows the page it is handed, so navigating is rebuilding with another page. A callback’s return value resolves the page’s promise and an exception rejects it.

var page = WebPage.ofHtml(DEMO)
        .on("goldberrySays", arguments -> "\"Java heard you\"");

WebViews.open(host, page) opens a page in a window of its own instead, and returns empty where no page can be opened.

Ask before offering one

The engine is the platform’s own, driven through a separate optional library, so the toolkit loads without it. Most machines cannot open a page, so an application asks first:

if (Goldberry.capabilities().contains(Capability.WEB_VIEW)) {
    return new WebView(WebPage.of(HANDBOOK));
}
return new Button("Open the handbook", () -> Desktop.browse(HANDBOOK));

WebViews.isAvailable() is the same question.

PlatformWhat the page is
X11, and XWaylandThe engine’s window, reparented into this one
macOSThe engine’s view, a subview of the window’s content view
WindowsThe engine’s child window
WaylandNothing. The widget refuses and says why

Wayland refuses it

Embedding means putting the engine’s window inside the application’s. Wayland does not allow a client to reparent a foreign surface, and no protocol proposes it. On a Wayland session the widget opens nothing and paints a message saying why, rather than dropping a loose window on the desktop. An application that wants a page there can ask for the X11 driver with -Dgoldberry.backend.videoDriver=x11, which runs the window under XWayland.

What a page cannot share the screen with

The page is a window above the frame, not a raster in it. Nothing painted can cover it: a popover, a tooltip or a toast that overlaps the page is invisible where they meet. A scroll does not clip it. opacity, transform and the frost material do not reach it. A dialog is the exception: while a modal is up the widget parks its page off the side of the window and brings it back when the dialog closes. A page is also opened parked and shown only once it reports itself loaded, with a spinner in its box until then.

Input is the page’s. The window system delivers clicks and keys to the engine directly, and on macOS the backend drops key events while a page holds the keyboard. Under X11 a window keeps presenting through the GPU with a page in it. A page is taken down on the engine’s thread, and its context outlives the application’s exit.

Signing in through a page

Two things a sign-in needs from a page cannot come from the page’s own script. The engine hands them over instead:

  • Where it is going. onNavigate(Predicate<URI>) is asked before every navigation, a server’s redirect included. False cancels it, and the page stays on the document it had. An OAuth redirect to a custom scheme comes back this way, with no loopback server.
  • Its cookies, HttpOnly ones included. cookies(URI) reads the engine’s jar for a URL. The answer is a CompletionStage<List<HttpCookie>> that completes on the UI thread.
private final WebViewController signIn = new WebViewController();

new WebView(WebPage.of(GRAFANA + "/login"))
        .onNavigate(uri -> {
            if ("myapp".equals(uri.getScheme())) {
                finish(uri.getQuery());
                return false;
            }
            if (uri.getPath().equals("/")) {
                signIn.cookies(URI.create(GRAFANA)).thenAccept(this::keepSession);
            }
            return true;
        })
        .controller(signIn)
        .withAttributes(Attributes.NONE.id("sign-in"));

A page opened with WebViews.open takes WebPage.onNavigate the same way and answers cookies(URI) itself. The predicate runs inside the engine’s decision, so it must answer at once, and one that throws lets the navigation go ahead. The widget asks the predicate of the page value it has now, so a rebuild with a new lambda needs no reload. A WebViewController is inert until its page has opened, and asking it then gives a stage that has already failed.

PlatformCookies fromNavigations asked about
LinuxThe engine’s cookie managerEvery frame’s: the engine does not say which frame
macOSThe engine’s cookie store, matched to the URL by the toolkitThe main frame’s
WindowsThe engine’s cookie managerThe main frame’s

On Linux and macOS every page in the process shares one cookie jar, so a session signed in to in one page can be read from any other.

A page can be given scripts that run before its own, on every navigation, which is where an embedding application defines the API its pages call. And the application can talk to the open page through the controller:

var page = WebPage.of(app.url()).initScript("window.Host = { version: 2 };").on("hostSend", this::received);
controller.postMessage("{\"type\":\"theme\",\"dark\":true}");

A page hears a posted message as a message event on its window, with the JSON as event.data.

A sign-out deletes what the page signed in with: deleteCookies(url, name) deletes the cookies the engine would send to url (all of them when name is null), and clearCookies() empties the jar. Both complete on the UI thread. On Linux and macOS every page shares one jar. WebViewSpec.userAgent(agent) sets the user agent the page sends from its first request, and the controller’s userAgent(agent) changes it later.

Styling

The widget builds a column with the class web-view, a stack with the class web-stage, and a canvas with the class web-surface that carries the id and sizes the page. All three default to flex-grow: 1, so a page fills the box it is given. The page’s own document is not in the toolkit’s tree, so no stylesheet or theme reaches it. An application that wants a page to follow the desktop’s light or dark setting reads Host.systemTheme() and writes the CSS.

Keyboard

The page’s own. The toolkit forwards nothing.