Browser Helpers¶
Small functions exported from the bundle for what a plugin otherwise rewrites. Each one is also on the Shared Bag, and copyWithFeedback and fetchObjectUrl live only there.
Decision¶
| When | Use |
|---|---|
| Every value placed into HTML a component builds from a string | escapeHtml |
| Any count in a label | plural |
A plural built by hand, such as n + ' items' |
plural instead |
Usage¶
import { downloadJson, pickJsonFile, errorText, plural, escapeHtml, debounce, generateGuid } from './configurationpage?name=myplugin_stolon.js';
downloadJson('channels.json', config.Channels);
pickJsonFile().then(function (data) { if (data) { applyImport(data); } },
function (err) { shared.setStatus('importStatus', err.message, true); });
shared.saveConfig(config).catch(function (err) {
errorText(err, 'Save failed.').then(function (text) { shared.setStatus('saveStatus', text, true); });
});
States and Modifiers¶
plural(count, one, many)gives the count, a space, and the word. Only a count of exactly 1 takesone.manydefaults toonewith an "s".escapeHtml(value)escapes&,<,>, and both quotes. Null and undefined become an empty string.debounce(fn, ms)runsfnonce calls pause forms(default 300) with the latest arguments. It hascancel().downloadJson(filename, value)saves a pretty printed JSON file, named "export.json" whenfilenameis empty.pickJsonFile()opens a file picker. It resolves to the parsed JSON, resolves tonullwhen cancelled, and rejects with "The file is not valid JSON." or "The file could not be read.".generateGuid({ compact })gives a random version 4 GUID, without dashes whencompactis true.errorText(err, fallback)always returns a promise of the reason a failed request gave, read from theError,error,detail,title, ormessageof a JSON body, elsefallback(default "Could not save.").shared.copyToClipboard(text)copies withnavigator.clipboardand falls back to a hidden textarea on HTTP dashboards. It resolves to whether it worked.shared.copyWithFeedback(btn, text, opts)copies and briefly swaps the button label to "Copied" or "Copy failed.".optstakescopiedText,failedText, andduration(default 1500 ms).shared.fetchObjectUrl(endpoint, params)fetches an authenticated endpoint underapiPrefixas a blob and returns an object URL. Revoke the URL when done.
Gotchas¶
copyToClipboardis also exported on its own for the Copy Field.
Reference¶
Generated from the code by scripts/build-docs.mjs. Edit the code, not this section.
generateGuid¶
function generateGuid(opts?: { compact?: boolean; }): string
Returns a random RFC 4122 version 4 GUID for keying new config entities on the client.
errorText¶
function errorText(err: any, fallback?: string): Promise<string>
Resolves to the reason a failed request gave, such as the Error of a 400 response's JSON body, or to fallback.
debounce¶
function debounce<A extends unknown[]>(fn: (...args: A) => void, ms?: number): ((...args: A) => void) & { cancel(): void; }
Returns a function that runs fn once calls have paused for ms milliseconds, with the latest arguments. The returned function has cancel() to drop a pending call.
downloadJson¶
function downloadJson(filename: string, value: unknown): void
Saves a value as a pretty-printed JSON file through the browser's download, for exporting configuration.
pickJsonFile¶
function pickJsonFile(): Promise<any>
Opens a file picker for a JSON file and resolves to its parsed value, or to null when the picker is cancelled. It rejects when the file is not valid JSON or cannot be read.
plural¶
function plural(count: number, one: string, many?: string | null): string
Returns the count, a space, and the matching word, such as "1 item" and "3 items". Only a count of exactly 1 takes the singular.
escapeHtml¶
function escapeHtml(str: unknown): string
Escapes a value for HTML text or a quoted attribute. null and undefined become ''.
copyToClipboard¶
function copyToClipboard(text: string): Promise<boolean>
Copies text to the clipboard, with a textarea fallback for HTTP dashboards. The promise resolves to true when the copy worked and never rejects. The shared bag's copyToClipboard calls it.
Example¶
Example Code¶
<!-- title: Browser Helpers -->
<div id="out"></div>
<div style="display: flex; flex-wrap: wrap; gap: 10px; margin-top: 14px;">
<button type="button" id="btnDownload" class="raised stolon-button stolon-secondary stolon-small"><span>Download JSON</span></button>
</div>
<script type="module">
const base = await window.__baseReady;
const list = base.createDefinitionList({ items: [] });
document.getElementById('out').appendChild(list.element);
const items = [
{ label: 'plural', value: base.plural(1, 'item') + ', ' + base.plural(3, 'item') + ', ' + base.plural(2, 'child', 'children'), mono: true },
{ label: 'escapeHtml', value: base.escapeHtml('<b>"Tom" & Jerry</b>'), mono: true },
{ label: 'generateGuid', value: base.generateGuid(), mono: true },
{ label: 'generateGuid compact', value: base.generateGuid({ compact: true }), mono: true }
];
list.setItems(items);
base.errorText(new Response(JSON.stringify({ title: 'Bad request' }), { status: 400 }), 'Could not save.')
.then((text) => list.setItems(items.concat({ label: 'errorText', value: text, mono: true })));
const searched = base.debounce((value) => list.setItems(items.concat({ label: 'debounce', value: 'ran once with ' + value, mono: true })), 300);
searched('a'); searched('ab'); searched('abc');
document.getElementById('btnDownload').addEventListener('click', () => base.downloadJson('channels.json', [{ name: 'News' }]));
</script>