JavaScript on a Verso site
Verso pages are plain HTML, so your scripts work the way they would anywhere. A few rules keep them friendly with the editor and with Elevate.
Anything in public/ is copied to the built site as it is, and served at the same address while you edit. Put scripts in public/js/ and load them from a template.
<script type="module" src="/js/docs.js"></script>
Modules are the easiest choice: they run after the page is parsed, they can import each other, and they keep their variables to themselves.
Fields don’t go in scripts
A template can’t put a field, list or condition inside <script> or <style>. Verso stops with “Template tags can’t go inside <script>.” and the line. To hand a value to a script, put it in the page and read it from there:
<section data-demo="spread" data-start="{{ page.date-iso }}">
<h2>{{ heading:text }}</h2>
</section>
document.querySelectorAll('[data-demo="spread"]').forEach((el) => {
const start = el.dataset.start;
// …
});
Your scripts run while you edit
The editor isn’t a copy of your page. It is your page, rendered by Verso with an editing layer on top. Your scripts load and run there too, which is good for previews and bad if a script rewrites text that someone is trying to edit.
While a page is open in the editor, its <html> element has a data-verso-editing attribute. Check for it, and leave fields alone:
const editing = document.documentElement.hasAttribute('data-verso-editing');
if (!editing) {
// Safe to rearrange the page: a reading-time badge, a carousel, a table of contents.
}
- Don’t replace or move field elements while editing. Fields carry
data-verso-field,data-verso-richanddata-verso-imageattributes. Rebuilding their markup cuts them off from the editor. - Don’t take the editor’s keys.
Ctrl Kor⌘Kand/open the command palette, andCtrl Zor⌘Zundoes. If your site has its own shortcut on one of them, turn it off while editing. - Adding things beside fields is fine. A copy button next to a code block, or a demo that only reads the page, works in both places.
Classes your script adds
Elevate compiles only the classes it can find in the files it scans. A class that exists only in a script is never compiled, so it does nothing.
A new site already scans its scripts. Its elevate/config/elevate.ts watches public/ and reads .js files:
Watch: ['./templates', './parts', './blocks', './public'],
FileTypes: ['html', 'js'],
If your site is older, or your scripts live somewhere else, add their folder to Watch and 'js' to FileTypes.
Then write each class list as a whole class="…" string, so Elevate’s pattern can find it. Building a class name out of pieces hides it.
// Found and compiled:
button.outerHTML = `<button class="font:small:medium pd:d2:d4 bd:round-pill bg-color:ink text:paper">Copy</button>`;
// Never compiled, because no class="…" string contains it:
el.classList.add('bg-color:' + tone);
Once a folder is scanned, every class string in it is checked like a template’s, so a mistake there stops the build and names the file and line.
A whole interface in classes
A script can build a toolbar, a dialog or a demo without a stylesheet of its own. This site's home page does: its stand-in editor bar, its dialogs and its demos are Elevate classes and nothing else. Three habits make that work.
- Write each look once, whole. Keep the class lists in one table at the top of the script and use them by name. A value the script puts inside the quotes, like
class="${look}", is skipped by Elevate, so the lists it reads are the ones in the table. - Change state with attributes.
aria-pressed,disabledandaria-expandedare styled by@pressed,@disabledand@expanded, so the script sets the attribute and the classes stay put. For a bigger change, swap one whole list for another. - Write out every list a choice can lead to. A script that lets someone pick columns can't glue
'grid:cols-' + n + '-fr'together. List the combinations it offers and look the choice up.
const LOOK = {
tool: 'class="row:y-center h:d10 pd-x:d3 bd:round-pill text:paper @hover:[bg-color:ink-2] @pressed:[bg-color:paper_text:ink]"',
};
const list = (s) => s.slice(7, -1);
button.className = list(LOOK.tool);
button.setAttribute('aria-pressed', 'true');
Colours that come from content, like a swatch for a colour someone picked, and sizes worked out while the page runs are the two things left for a style attribute.
If you do need CSS of your own, put it in a file in elevate/extend/, add the file to Extend in elevate/config/elevate.ts, and start each of its class names with a hyphen, like -chart. Elevate leaves those alone. That CSS can't use the site's tokens, so the Design panel won't reach it.
The editor recompiles CSS whenever a file in public/ changes, scripts included, so a new class in a script is styled as soon as you save it.
Show state with attributes, not classes
Swapping whole class strings to show that something is open or current is fragile, because every combination has to be written out somewhere. Elevate 1.3 styles elements by their ARIA and open state instead. Write both looks in the template, and let the script set one attribute:
<a href="/docs/" class="text:ink-3 @current:[text:ink_font:semibold]">Docs</a>
<button aria-expanded="false" class="@expanded:[bg-color:paper-2]">Menu</button>
link.setAttribute('aria-current', 'page');
button.setAttribute('aria-expanded', String(open));
menu.hidden = !open;
| State | Matches |
|---|---|
@current | aria-current, unless it is "false" |
@expanded | aria-expanded="true" |
@selected | aria-selected="true" |
@pressed | aria-pressed="true" |
@open | [open], on details and dialog |
The hidden attribute always hides an element, even one with a display class like row or grid, so element.hidden = true is all it takes. The attributes also tell screen readers what changed, which a class never does.
Reading the site’s pages
With "index": true in verso.json, a build writes /pages.json: every live page with its title, description, headings and text. It is what a search box or a “next page” link needs. See Search, sitemaps and 404s for its shape.
const base = document.documentElement.dataset.base || '';
let pages = [];
try {
pages = await (await fetch(`${base}/pages.json`)).json();
} catch {
// Turned off: "index" isn't true in verso.json.
}
The editor serves pages.json too, made fresh from the content, so a search box or a “next page” link works while you edit.
A site in a sub-folder
When verso.json has a "base", like "/notes", the build adds it to every address in the HTML, but it can’t see addresses a script builds. The built <html> carries data-base="/notes" for that, as in the example above. In the editor, and on a site without a base, it isn’t there, so fall back to an empty string. See Feeds and sub-folders.