How-to
Website
Web app
Desktop / phone
Draw into a node a script made
Some libraries make a node and leave it empty for the page to fill: an editor's tooltip, a map's popup, a chart's legend. To fill it, use Portal(into: node) { … }. The library keeps the node's place, its keys and its focus; the page draws what is in it. This page starts a CodeMirror editor whose hover tooltip shows the line under the pointer, drawn by the page:
Needs: src/editor.js, a CodeMirror bundle in public/vendor/, and two settings in webfluent.app.json, each shown below.
page Edit(path: "/edit", title: "Edit", description: "An editor whose tooltip the page draws.") {
state tip: String? = null
state words = ""
action opened(id: String, text: String) {
tip = id
words = text
}
action closed(id: String) {
if tip == id { tip = null }
}
Heading("Edit").h1
Host(mount: (n) => startEditor(n, opened, closed), cleanup: (view) => view.destroy())
if let id = tip {
Portal(into: editorHost(id), data-popup: "hover") {
Text(words)
}
}
}
This script starts the editor. It calls CodeMirror as CM, which the next step provides:
// src/editor.js
// CodeMirror places each tooltip and keeps its keys; the node it makes is
// left empty, and the page draws what is in it.
const tooltips = new Map();
let made = 0;
/**
* The node CodeMirror made for a tooltip, or null once it has gone.
* @param {string} id
* @returns {HTMLElement|null}
*/
function editorHost(id) {
return tooltips.get(id) ?? null;
}
/**
* An editor in `node`. `opened(id, text)` hears a tooltip open, with the
* words under the pointer; `closed(id)` hears it close.
* @param {HTMLElement} node
* @param {(id: string, text: string) => void} opened
* @param {(id: string) => void} closed
*/
function startEditor(node, opened, closed) {
const hover = CM.hoverTooltip((view, pos) => ({
pos,
create() {
const id = `hover-${++made}`;
const dom = document.createElement("div");
tooltips.set(id, dom);
opened(id, view.state.doc.lineAt(pos).text);
return { dom, destroy() { tooltips.delete(id); closed(id); } };
},
}));
return new CM.EditorView({ parent: node, extensions: [CM.basicSetup, hover] });
}
CodeMirror comes in several npm packages that must share one copy of @codemirror/state, and no CDN file exports EditorView, basicSetup and hoverTooltip together. Bundle the three into one module of your site's own, once, with esbuild (it needs Node):
$ npm install --save-dev esbuild codemirror @codemirror/view
$ mkdir -p vendor public/vendor
$ printf '%s\n' \
$ 'export { EditorView, hoverTooltip } from "@codemirror/view";' \
$ 'export { basicSetup } from "codemirror";' > vendor/codemirror.js
$ npx esbuild vendor/codemirror.js --bundle --format=esm --minify --outfile=public/vendor/codemirror.js
Then load the bundle as a module named CM. CodeMirror writes its styles from script, which the page's Content-Security-Policy allows only with style_elements:
{
"meta": {
"scripts": [{ "src": "/vendor/codemirror.js", "module": true, "as": "CM" }],
"style_elements": true
}
}
How it works
The bundle is served from your own site, so it needs no integrity hash; run the esbuild line again when you update CodeMirror.
The page hands Host's node to startEditor, with two actions the script calls when a tooltip opens and closes. opened keeps the tooltip's id and the words in state; if let draws the portal while there is an id, and editorHost(id) names the node CodeMirror made for it. A portal behaves this way:
- It reads its target again.
into:is read like any other expression: when a state or a list item it reads changes, it is read again. A tooltip that replaces another has a new id, so the block follows it to the new node. - It moves; it is not drawn again. When
into:names another node, the same box moves there with its nodes and their state: a field half typed in, a list scrolled halfway.nullkeeps the box aside, and when a node is named again the same nodes come back. - It belongs to where it is written. Its handlers, its
emit, the state it reads and changes, and itsmount:andcleanup:belong to the page or the component it is written in. The node is only where they are drawn. Amount:inside the block runs once the block is drawn and in place, so it meets its node in the document when the node it goes into is there. - It leaves with its scope. When the page, the branch or the list item it is written in leaves, the box leaves the node with it. The node belongs to the library, and stays.
- The box adds nothing to the layout. It is a
divwithdisplay: contents, so the node lays out the block as if the box were not there. Anid:, aclass:,data-*andaria-*go on the box, asdata-popup:does here. - It can target a handle.
Portal(into: panel)draws into the element aref: panelnames, even one written further down the page. Where it goes is read once more when the drawing is over and the page is in the document, so an element of the page's own thatdocument.getElementByIdfinds is found too. A handle is not a state: an element the handle names only later, in anifthat opens afterwards, is not followed. - Its events bubble from where it is drawn. A press inside the block bubbles through the node it is in and that node's parents, not through the elements around the place it is written. An
on clickon aStackthat holds the portal does not hear it. Put the handler on the portal, or inside its block. showdoes not hide it.showhides what is drawn in its own place, and a portal's block is drawn somewhere else. Remove it withif, or keep it aside withinto: null.- The pre-rendered page has only a marker. The static paint (the HTML the build pre-renders for a page) has a marker where a portal is, and nothing of its block. The live page draws the block once its script has run. A test that looks at a portal runs in a browser (Testing).
Troubleshooting
| What you see | What to do |
|---|---|
|
|
Give it |
| A click inside the block does not reach a handler around the portal | Events bubble from the node the block is drawn in: put the handler on the portal, or inside its block |
|
The block stays on screen inside a |
Use |
| The pre-rendered page lacks the block | Expected: the block is drawn once the page's script runs |
Variations
A list that the library keeps (an editor's completions, each row a node it made) is a keyed for of portals. A press on a row should leave the focus in the editor: on mousedown(e) { e.preventDefault() } does that, and on click still runs. This fragment of a page draws one portal per row of a Completions store:
for row, i in Completions.rows by i {
Portal(into: editorHost(row.id), data-popup: "row") {
Text(row.label) {
on mousedown(e) { e.preventDefault() }
on click { Completions.pick(i) }
}
}
}