Skip to content

Front-end helpers (window.fp)

Core 0.4.98 provides a window.fp namespace with shared front-end helpers that mirror Python filters and eliminate the need for private copies in plugins.

The helpers live in fp-helpers.js. base.html.j2 and public_base.html.j2 load it in <head>, without defer, so window.fp exists before any script of the page runs. An inline script can call fp.* from its first line, including after an await. Before 0.4.107 the helpers were in the deferred scripts.js, so a page script that reached fp.* before it had run failed with fp is not defined.

fp-helpers.js does not touch the document when it loads: fp.copy, fp.notify and fp.confirm only reach document.body when they are called. The delegated handlers below stay in the deferred scripts.js.

Escaping

fp.escapeHtml(s) / fp.escapeAttr(s)

Escape HTML special characters: & < > " ' → &amp; &lt; &gt; &quot; &#39;.

  • null / undefined returns ""
  • Any other value goes through String()
  • Both functions are identical (attribute escaping uses the same rules)
fp.escapeHtml('<script>alert("xss")</script>')
// "&lt;script&gt;alert(&quot;xss&quot;)&lt;/script&gt;"

fp.escapeHtml(null)  // ""
fp.escapeHtml(42)    // "42"

Use when building HTML strings in JavaScript to prevent XSS.

Formatting

All formatting helpers return "—" for null, undefined, or non-numeric input.

fp.formatBytes(n, {decimals: 1, none: "—"})

Format bytes with binary units (B, KB, MB, GB, TB, PB). Steps of 1024.

  • Bytes (< 1024) are integers with no decimal: 0 B, 512 B, 1023 B
  • Every larger unit uses decimals (default 1): 1.0 KB, 1.5 MB, 470.8 KB
  • Sign is preserved: -512 B, -1.5 KB
  • Values ≥ 1024 PB stay in PB
fp.formatBytes(0)         // "0 B"
fp.formatBytes(1024)      // "1.0 KB"
fp.formatBytes(1536)      // "1.5 KB"
fp.formatBytes(1048576)   // "1.0 MB"
fp.formatBytes(null)      // "—"
fp.formatBytes(1024, {decimals: 2})  // "1.00 KB"

Output matches the Python format_bytes filter (same strings for the same inputs).

fp.formatDuration(seconds)

Format duration from seconds.

  • < 1s → 850ms (milliseconds as integer)
  • < 60s → 42.5s (one decimal)
  • < 1h → 7m 6s
  • ≥ 1h → 1h 12m
fp.formatDuration(0.85)   // "850ms"
fp.formatDuration(42.5)   // "42.5s"
fp.formatDuration(426)    // "7m 6s"
fp.formatDuration(4320)   // "1h 12m"

Output matches the Python format_duration filter.

fp.formatDurationMs(ms)

Same as fp.formatDuration but input is milliseconds.

fp.formatDurationMs(850)    // "850ms"
fp.formatDurationMs(42500)  // "42.5s"

Output matches the Python format_duration_ms filter.

fp.timeAgo(isoOrDate)

Relative time from an ISO string or Date object.

  • < 5s → just now
  • < 60s → 12s ago
  • < 1h → 5m ago
  • < 24h → 3h ago
  • < 7d → 2d ago
  • ≥ 7d → ISO date 2026-11-16
fp.timeAgo(new Date(Date.now() - 65000))  // "1m ago"
fp.timeAgo("2026-11-15T10:00:00Z")        // "2026-11-15" (if > 7 days)

Output matches the Python format_relative_time filter.

Clipboard

fp.copy(text) → Promise

Copy text to the clipboard. Uses navigator.clipboard in secure contexts, falls back to document.execCommand('copy') in plain HTTP.

Returns a Promise that resolves on success, rejects on failure.

fp.copy('Hello, world!')
    .then(() => console.log('Copied'))
    .catch(() => console.log('Failed'));

This is the core's existing copyText function (used by the traceback copy button), now public.

Notifications

fp.notify(message, level, opts)

Show a toast notification, drawn as the UI kit's notification: soft tint of the level, opaque, icon and title in the level's colour.

Parameters: - message — Message text (string) - level — "info", "warning", "error", "success" (default "info"; "danger" is read as "error") - opts — Optional object: - title — Toast title (default: the level's label, "Info", "Success", "Warning" or "Error"; the legacy showNotification() keeps "Task Update") - link — URL to open in a new tab - linkLabel — Link text (default "View details") - action — {label, onClick} — Inline button (e.g., {label: "Undo", onClick: undoFn}) - sticky — Boolean: keep the toast until manually closed (default false, auto-dismiss after 5s)

fp.notify('Task completed', 'success');

fp.notify('Database backed up', 'info', {
    title: 'Backup',
    link: '/backups/123',
    linkLabel: 'Download'
});

fp.notify('File deleted', 'warning', {
    action: {
        label: 'Undo',
        onClick: () => restoreFile()
    }
});

The global showNotification(message, level, link, {sticky}) still works (backward compatibility), delegating to fp.notify.

Confirmation

fp.confirm(message, opts) → Promise<boolean>

Since core 0.4.115.

Ask the user to confirm an action, in a modal that follows the app's theme. Use it instead of the browser's confirm(): that box ignores the theme, blocks the whole page, and once the user ticks the browser's "prevent this page from creating additional dialogs" it returns false without showing anything, so the action can no longer be confirmed.

Parameters: - message — The question. Inserted as text, never as HTML; line breaks (\n) are kept - opts — Optional object: - title — Modal title (default "Are you sure?") - confirmLabel — Confirm button text (default "Confirm") - cancelLabel — Cancel button text (default "Cancel") - danger — true (default): red button and red top border, focus on Cancel. false: primary button, focus on Confirm (Enter confirms)

Returns: a Promise resolved once the modal is closed: true on Confirm, false on Cancel, Escape or a click outside.

deleteBtn.addEventListener('click', async () => {
    if (!await fp.confirm(`Delete the key "${name}"?`, {confirmLabel: 'Delete'})) return;
    await fetch(url, {method: 'DELETE'});
});

fp.confirm('Publish the draft?', {danger: false, confirmLabel: 'Publish'})
    .then(ok => ok && publish());

On a page without the Bootstrap/Tabler JS (window.bootstrap or window.tabler), it falls back to window.confirm(message). For a button rendered on the server, ButtonWidget(confirm=...) renders the same kind of modal without JavaScript.

Polling

fp.poll(fn, intervalMs, opts) →

Run a function on an interval without overlapping executions. fn may return a Promise.

Parameters: - fn — Function to run (async or sync) - intervalMs — Interval in milliseconds - opts — Optional object: - pauseWhenHidden — Boolean: pause while document.hidden (default true) - stopOnError — Boolean: stop polling if fn throws (default false)

Returns: Controller object with .stop() method.

const poller = fp.poll(async () => {
    const data = await fetch('/api/status').then(r => r.json());
    updateUI(data);
}, 5000);

// Later: stop polling
poller.stop();

Runs fn immediately, then schedules the next run after intervalMs. If the previous run is still going, the next tick is skipped (no overlap). When the page is hidden (document.hidden), polling pauses by default.

Text

fp.ellipsize(text, max) → string

Shorten a text to at most max characters, the last one being …. A text that fits is returned unchanged; null / undefined returns "". It counts characters, not UTF-16 units, so an emoji is never cut in half. The result is text: escape it (fp.escapeHtml) before putting it in innerHTML or in a chart option that takes markup (legend, tooltip).

fp.ellipsize('send_daily_report_to_all_users', 18)  // "send_daily_report…"
fp.ellipsize('short', 18)                            // "short"

Use it where the space is fixed and the full text is shown elsewhere: a donut's centre label, an axis category, a table cell with the full name in its title.

API errors

fp.errorText(body, status) → string

The reason a failed API call gives, as one line of text for fp.notify, an alert or an Error. body is the response body already read (parsed JSON, or text), status the HTTP status.

Body Result
{"detail": "Task not found"} (an HTTPException) Task not found
{"detail": [{"loc": ["query", "limit"], "msg": "..."}]} (FastAPI validation, 422) limit: ..., one <field>: <msg> per entry joined by ;; a nested field reads items.0.name
{"message": "..."} the message
a text that is not an HTML page the text
empty, null, an HTML error page, any other JSON HTTP <status> (Request failed without a status)
const response = await fetch(url, {method: 'POST', headers: {'Accept': 'application/json'}});
if (!response.ok) {
    const body = await response.json().catch(() => null);
    fp.notify(fp.errorText(body, response.status), 'error');
}

Send Accept: application/json: the core answers a refused call (401, 403, 404) with a page otherwise, and its detail is lost. The result is text: escape it (fp.escapeHtml) before putting it in innerHTML. Reading body.detail || '...' by hand shows [object Object] for a 422, because its detail is a list.

CSV

fp.csv(rows, {headers}) → string

The text of a CSV file, RFC 4180: every field between double quotes, quotes inside a field doubled, each line ended by CRLF, so a comma, a quote or a line break stays inside its field. A value that is not a number and starts with =, +, -, @, a tab or a carriage return gets a leading ': a spreadsheet would otherwise run it as a formula when the file is opened. null and undefined give an empty field.

rows are arrays of values, or objects whose values are read in the order of headers; headers, when given, is the first line.

fp.csv([['Function', 'Runs'], ['a,"b"', 2], ['=1+1', 3]])
// "Function","Runs"\r\n"a,""b""","2"\r\n"'=1+1","3"\r\n

fp.csv(runs, {headers: ['name', 'status', 'duration']})   // runs: [{name, status, duration, ...}]

fp.downloadCsv(filename, rows, {headers})

Downloads the same text as a file. It starts with a UTF-8 byte order mark, so Excel reads accented text right (other spreadsheets ignore it).

fp.downloadCsv(`task_durations_${new Date().toISOString().slice(0, 10)}.csv`, rows, {headers});

Charts

A chart library paints its SVG with the colours of its options, not with the page's CSS. A chart drawn with ApexCharts' defaults therefore keeps dark grey labels (1.6:1 on the dark card), light grid lines, white rings between donut slices and a light tooltip in the dark theme. These helpers give a chart the theme's colours and tell the page when the theme changes. The core does not load a chart library: the page that draws a chart loads it (see ApexCharts 4.7.0).

fp.chartTheme(el) → object

The current theme's colours, read from the core's CSS variables when called:

Key Variable Use
mode data-bs-theme "light" or "dark"
text --c-text legend, titles, values
muted --c-text-muted axis labels and titles (4.5:1 or more in both themes)
grid --c-border-str grid lines, axis lines and ticks
background --c-surface the card behind the chart: slice separators, marker rings
tones.blue / teal / violet --c-accent, --c-teal, --c-purple category hues, for series that are only told apart (UI kit rules)
tones.success / warning / danger / info / neutral --c-success, --c-warning, --c-danger, --c-info, --c-text-subtle state colours, for a series or a threshold that IS good or bad news

el (optional) is the element the chart is drawn in: a chart inside a data-bs-theme island takes the island's theme. On a page without the core CSS (its own <head> without ui-kit.css), each key falls back to the core's value for that theme.

Any library can use it, e.g. a canvas chart:

const t = fp.chartTheme(el);
new Chart(el, {type: 'line', data, options: {scales: {x: {ticks: {color: t.muted}, grid: {color: t.grid}}}}});

fp.apexOptions(options, el) → object

ApexCharts options that follow the theme, merged UNDER the chart's own options (yours win; objects are merged key by key, lists and values replace). It sets:

  • the axis labels, axis titles, legend, chart title and subtitle colours, grid, axis border and tick colours, a transparent background, theme.mode and tooltip.theme;
  • markers.strokeColors and, on pie / donut / polarArea, the slice separators to the card colour (ApexCharts draws them white), and the donut's centre labels;
  • the radar polygons and the radial bar's track;
  • dataLabels: {enabled: false} on axis charts (line, area, bar...): the tooltip already gives each value, and an area chart with a few hundred points otherwise prints one label per point. Pass dataLabels: {enabled: true} to keep them. Pie charts keep their percentages;
  • colors: ApexCharts' own first palette, so series keep their hues when the theme switches (with theme.mode: "dark" ApexCharts would move a chart without colors to another palette).

It never modifies options, and the result shares no list or object with it: ApexCharts writes into the options it is given, and the page reuses options on each theme switch.

Apply it again when the theme changes:

const el = document.getElementById('durationChart');
const options = {
    chart: {type: 'bar', height: 380},
    series: [{name: 'Average duration', data: durations}],
    xaxis: {categories: names.map((n) => fp.ellipsize(n, 18)), title: {text: 'Function'}},
    yaxis: {title: {text: 'Duration'}, labels: {formatter: (v) => fp.formatDuration(v)}},
};
const chart = new ApexCharts(el, fp.apexOptions(options, el));
chart.render();
const stop = fp.onThemeChange(() => chart.updateOptions(fp.apexOptions(options, el), false, false));
// before chart.destroy(): stop();

Colours the helper cannot reach, because they sit inside list items of yours: annotation labels (ApexCharts gives them a white background). Give them the theme's colours yourself, e.g. label: {style: {color: t.tones.danger, background: 'transparent'}}.

fp.onThemeChange(callback) → function

Calls callback(theme) ("light" or "dark") each time the page switches theme, whoever switches it: the topbar toggle or a plugin's own control. It watches data-bs-theme on <html>, the attribute every switch sets, and calls back once per real change. Returns a function that stops listening; call it before destroying the chart.

The same switch is dispatched on document as the fp:themechange event (event.detail.theme), for code that prefers a listener:

document.addEventListener('fp:themechange', (e) => redraw(e.detail.theme));

A page whose chart is not an SVG library (plain HTML nodes, CSS) does not need these helpers: its stylesheet reads the CSS variables (var(--c-surface), var(--c-text), var(--c-border)) directly and follows the theme by itself.


Delegated handlers

Core installs these handlers on document.body once. No plugin-specific JS needed.

[data-copy]

Click copies the attribute value to the clipboard and briefly shows a check icon.

Value interpretation: - Plain text → copied as is - Starts with # → treated as a CSS selector; copies that element's textContent

<button data-copy="ssh-keygen -t ed25519">Copy command</button>

<pre id="ssh-key">ssh-ed25519 AAAAC3Nza...</pre>
<button data-copy="#ssh-key">Copy SSH key</button>

The button's innerHTML is replaced with <i class="ti ti-check"></i> Copied for 1.5s, then restored.

[data-confirm]

Forms, buttons, and links with data-confirm ask fp.confirm(message) before submission/navigation. The event is stopped, then replayed once if the user confirms; a form is resubmitted with the button that submitted it, so that button's name/value are still posted.

<form method="post" action="/delete" data-confirm="Delete this item?">
    <button type="submit">Delete</button>
</form>

<button type="button" class="js-danger" data-confirm="Are you sure?">
    Danger
</button>  <!-- the plugin's JS binds .js-danger: no inline handler -->

<a href="/reset" data-confirm="Reset everything?">Reset</a>

Migration note: A plugin with its own data-confirm handler should drop it. Core only handles elements without data-confirm-handled (set that attribute if you want to keep a custom handler for a specific element).


ApexCharts 4.7.0

Core vendors ApexCharts 4.7.0 (the last MIT-licensed 4.x; version 5.x switched to a dual license requiring payment for platforms used by others).

Location: /static/vendor/apexcharts-4.7.0/

Files: - apexcharts.min.js (576 KB) - apexcharts.css (14 KB) - LICENSE (MIT) - README.md (version, checksums, why 4.7.0, update procedure)

Plugins should not load ApexCharts from base.html.j2 (it would add ~600KB to every page). Include it only in templates that need charts:

<script src="/static/vendor/apexcharts-4.7.0/apexcharts.min.js"></script>
<link href="/static/vendor/apexcharts-4.7.0/apexcharts.css" rel="stylesheet">

The core /static route serves these files anonymously with ETag caching.

A chart drawn with ApexCharts' defaults is unreadable in the dark theme (dark labels, light grid, white slice separators): build its options with fp.apexOptions().

Why 4.7.0? Version 5.x introduced a dual license: free only below a revenue threshold, paid OEM for platforms. 4.7.0 stays MIT and provides all chart types used in FastPluggy plugins (line, stepline, bar, x-axis annotations) with rendering identical to 8.x. Do not upgrade to 5.x without reviewing the license terms.


Public base template

public_base.html.j2 is a bare centered page for unauthenticated flows: login, register, public package index.

Includes: - Anti-FOUC script (applies saved theme before paint) - Vendored Tabler CSS + themes - Tabler Icons - Core styles.css - Core fp-helpers.js in <head> (so window.fp exists before the page content) and scripts.js - Tabler JS (Bootstrap 5)

Blocks: - title — Page title (default: {{ app_name | default('FastPluggy') }}) - head_extra — Additional <head> content - content — Page body - scripts — Additional scripts

Variables: - container_class — Container class (default: container-tight py-4) - version — App version (for cache busting)

{% extends "public_base.html.j2" %}

{% block title %}Login{% endblock %}

{% block content %}
<div class="card">
    <div class="card-body">
        <h2>Sign in</h2>
        <form method="post">
            <!-- login form -->
        </form>
    </div>
</div>
{% endblock %}

Error pages (error_base.html.j2) now extend public_base.html.j2 instead of being standalone. Rendering is byte-identical.

Status badges and tags

fp.statusBadge(value, colors, label) / fp.tag(text) → string

The HTML of the UI kit's status badge and tag, as the status_badge and tag filters draw them (escaped). fp.statusBadge takes the colour from colors (your own words), then from the core's shared words read from <html data-fp-status-tones>, else grey.

cell.innerHTML = fp.statusBadge(row.status) + ' ' + fp.tag(row.topic);

fp.statusTone(value) → string

The tone of a shared status word, as the status_tone filter gives it: 'success', 'danger', 'warning', 'info' or 'secondary' (also for a word the core does not know). Case-insensitive; spaces and dashes read as _. The words come from <html data-fp-status-tones>; see the UI kit for the table.

counter.classList.add('text-' + fp.statusTone('requeued'));   // text-secondary