Fidus Writer Toolkit — reusable TypeScript utilities, UI helpers and styles originally written for Fidus Writer but usable in any browser project.
import {escapeText, addAlert} from "fwtoolkit"
import {convertDataURIToBlob} from "fwtoolkit/blob"The source is written in TypeScript and ships with declaration files:
import {Dialog} from "fwtoolkit/dialog"The package ships the styles for its UI components under fwtoolkit/css/.
Load colors.css and tokens.css first (they define the design tokens), then
the component styles you need. If the host page has not already applied a CSS
reset, load reset.css before the component styles:
<link rel="stylesheet" href="node_modules/fwtoolkit/css/reset.css" />
<link rel="stylesheet" href="node_modules/fwtoolkit/css/colors.css" />
<link rel="stylesheet" href="node_modules/fwtoolkit/css/tokens.css" />
<link rel="stylesheet" href="node_modules/fwtoolkit/css/dialog.css" />
<link rel="stylesheet" href="node_modules/fwtoolkit/css/buttons.css" />New stateful components request their own sheet with
ensureCSS(staticUrl("css/fwtoolkit/<component>.css")). Hosts that preload the
complete css/fwtoolkit.css bundle can omit individual links; both paths use
the same source sheet. Configure staticUrl() through initSettings() so
runtime component CSS resolves correctly in bundled, scoped, and standalone
hosts.
css/tokens.css defines the semantic Design 5 layer (--fw-*): typography
(Poppins UI typeface, size/weight/line-height scales), colours, radii, sizing,
spacing, motion and z-index. New component code should use these tokens.
The legacy token names in css/colors.css (--main-*, --cs-*,
--overview-*, --input-*, --tabs-*, …) are retained and now alias the
semantic layer, so existing host stylesheets keep working unchanged.
Contrast rules are enforced by test/contrast.test.ts:
--fw-brand(#50c95f) is a fill only — it never reaches 4.5:1 on white. Text on green uses--fw-text-on-brand(#292929, ~6.8:1).--fw-accent(blue) is safe for text and for white-on-accent.- Non-text control strokes use
--fw-border-control(#8c8c8c, ≥3:1). --fw-text-secondaryis darkened to#656565so secondary text still passes AA on--fw-surface-2; the mock's lighter#848383is available as--fw-text-tertiaryfor large/decorative text only.
Wrap a labelled field in .fw-floating-field to get a Material-style text
field: the label sits inside the field while it is empty and unfocused, and
rises above it on focus or once the field has content.
<div class="fw-floating-field">
<label for="title">Title of publication</label>
<input type="text" id="title" placeholder=" " />
</div>
<script type="module">
import {initFloatingLabels} from "fwtoolkit"
initFloatingLabels() // call again for fields added later, e.g. dialogs
</script>- The input needs a placeholder — a single space is enough.
- Focus is handled entirely in CSS (
:focus-within);initFloatingLabels()only tracks the "has content" state (.fw-filled) and the disabled state. - Call
initFloatingLabels(dialog.dialogEl)after opening a dialog, since the dialog body does not exist until then. - Motion is disabled under
prefers-reduced-motion.
FocusScope provides initial focus, a dynamically calculated tab loop for
modal UI, focus restoration, and isolation of background content. Multiple
scopes form a stack, so only the top modal scope handles Tab and nested dialogs
do not compete for keyboard input.
import {FocusScope} from "fwtoolkit"
const scope = new FocusScope({
element: dialogElement,
modal: true,
initialFocus: "#dialog-name",
restoreFocus: invokerElement
})
scope.activate()
// The host owns dismissal policy, including Escape and backdrop clicks.
scope.deactivate() // restores focus and releases all listenersmodal: falsesets and restores focus without trapping it.- Repeating
activate()ordeactivate()is safe; an instance can be reused. restoreFocus: falseleaves focus where it is when the scope closes.getPortalsmay return focusable overlay elements rendered outsideelement, such as menus or tooltips, so modal isolation does not hide them.onStackChangeruns after any scope is pushed or popped, allowing an active scope to update focus containment and portal accessibility when a nested overlay opens or closes.- The element itself becomes the programmatic focus fallback when it has no
focusable controls. Its original
tabindexis restored on deactivation. FocusScopehas no stylesheet requirement. The host remains responsible for dialog semantics, visible focus styling, Escape handling, and dismissal.
All interactive components use a single :focus-visible ring
(--fw-focus), keep their keyboard operability and ARIA semantics, and honour
prefers-reduced-motion. The file dialog is a Finder-style column browser with
role="tree"/role="treeitem", roving tabindex, arrow-key navigation and a
clickable breadcrumb.
In Fidus Writer the CSS is copied automatically to the static files directory
by the copy_fwtoolkit_css postinstall step.
Implementations and their public option/result types are exported from the package root. ProseMirror-specific helpers are the exception and are available only from dedicated subpaths.
| Area | Components and utilities |
|---|---|
| Dialogs & actions | PromptDialog, ConfirmActionDialog, ActionDialog<T>, EditableListDialog, ActionChooserDialog |
| Forms & inputs | FileInputField, BooleanSwitch, OneTimeCodeField, FormErrorSummary, DestinationSettingsForm, RemoteOptionsField, TokenInput, GridSizePicker |
| Files & media | ResourceField, AttachmentField, AttachmentList, ImagePreviewField, MediaCardGrid |
| Lists & ordering | SortableList<T>, sortable TwoPaneSelector |
| Navigation | TreeView, NavigationDrawer, DirectoryNavigator |
| Menus & toolbars | ApplicationMenuController, ActionToolbar, OverflowActionBar, IconButtonGroup |
| Data & identity | CategoryFilterController, AvatarLabel, PermissionBadge / AccessRightIndicator |
| Export | ExportFormatRegistry<T>, ExportMenuBuilder<T> |
| Feedback & focus | InlineStatus, FocusScope |
| Utilities | saveFile, saveBlob, ClipboardHelper, waitForElement, runWithProgress |
| Editor integration | nextSelection from fwtoolkit/prosemirror/next_selection |
- Field and navigation constructors mount into the supplied
domelement or expose an element for the host to append. Calldestroy()when the host view is removed; repeated calls are safe and release listeners, timers, observers, pending requests, and temporary overlay nodes. - Dialog presets return a promise from
init(). Submit, cancel, Escape, backdrop/close, anddestroy()settle the active session. Callinginit()again while open returns the same promise; reopening after settlement starts a fresh session. - Controlled fields report proposed changes through callbacks. The host accepts
them by calling
setValue()/setItems(); this is intentional for remote options, tokens, and other values that require persistence or validation. - Async controls expose busy state and prevent duplicate submissions. Routine progress uses polite status regions; errors do not render exception details.
- Library-authored labels use
gettext(). Host-provided labels and descriptors remain the host's localization responsibility.
import {PromptDialog} from "fwtoolkit"
const result = await new PromptDialog({
title: "Rename item",
label: "Name",
value: "Untitled",
required: true,
maxLength: 120,
validate: value => (value.trim() ? null : "Enter a name.")
}).init()
if (result.status === "submitted") {
await host.saveName(result.value)
}ActionDialog<T> accepts either a reusable field adapter or a render/reader
pair. Its submit callback returns {ok: true, value} or
{ok: false, message?, errors?}; the shell owns busy state and links field
errors through FormErrorSummary.
DestinationSettingsForm renders host-defined text, password, URL, number,
textarea, select, and checkbox descriptors. Visibility predicates see current
control values, but hidden fields are omitted from getValues() and submit
payloads. Password controls use autocomplete="new-password", and teardown
clears their values.
import {DestinationSettingsForm} from "fwtoolkit"
const form = new DestinationSettingsForm({
dom: document.querySelector("#settings"),
fields: [
{
id: "mode",
type: "select",
label: "Mode",
options: [
{value: "local", label: "Local"},
{value: "remote", label: "Remote"}
]
},
{
id: "token",
type: "password",
label: "Credential",
visible: values => values.mode === "remote",
required: true
}
],
onSubmit: async visibleValues => {
await host.saveSettings(visibleValues)
}
})The toolkit does not define providers, endpoints, request headers, response parsing, authentication, secret storage, or logging. Thrown submit failures become the generic localized message “Settings could not be saved.”
The registry stores ordered metadata and host actions. hidden and disabled
may be booleans or predicates over a host context; activation rechecks
disabled. Export eligibility, serialization, conversion, and exporter
selection remain outside the toolkit.
import {ExportFormatRegistry, ExportMenuBuilder} from "fwtoolkit"
const registry = new ExportFormatRegistry([
{id: "html", label: "HTML", action: context => host.exportHtml(context)},
{
id: "pdf",
label: "PDF",
disabled: context => !context.canPdf,
action: context => host.exportPdf(context)
}
])
const entries = new ExportMenuBuilder(registry).build(hostContext)OverviewMenuView consumes the resulting entries and skips disabled options
with both pointer and keyboard navigation.
ActionToolbar is the single visible-action renderer. OverflowActionBar
composes it, measures rendered geometry, observes resize/font changes, and moves
hidden actions into ApplicationMenuController without guessing item widths.
Call refresh() after mounting into a previously hidden layout. Sortable and
transfer controls always provide keyboard move controls in addition to pointer
dragging.
saveFile(data, options?)andsaveBlob(blob, options?)preserve MIME data, prefer a user-chosen location when available, and report cancellation as a normal result.ClipboardHelpercopies text or HTML with a fallback and injected notification callbacks.waitForElementsupports explicit timeout and abort signals.runWithProgressadapts promise-based work toProgressTask, propagates progress/cancellation, and guarantees cleanup.OneTimeCodeFieldclears completed codes synchronously and never logs or retains them.
import {nextSelection} from "fwtoolkit/prosemirror/next_selection"
const selection = nextSelection(editor.state, editor.state.selection.from, 1)
if (selection) {
editor.dispatch(editor.state.tr.setSelection(selection))
}nextSelection returns the next TextSelection or valid GapCursor, or
undefined at a document boundary. It is not exported from the root and adds
no ProseMirror imports to non-editor consumers. prosemirror-gapcursor is a
peer dependency; editor hosts must install it alongside the existing
ProseMirror peers.
Live demos are published on Forgejo Pages:
https://fiduswriter.pages.fiduswriter.org/fwtoolkit/
To build and deploy the demos yourself, run:
npm run build
./scripts/deploy-pages.shFor local verification, stage the same files without pushing the pages
branch:
npm run build
npm run stage:pages
python3 -m http.server 8080 --directory .pages-buildCopy demo/ui/focus-scope.html as the starting
point for a new component demo. Keep its light/dark, scoped-CSS, and narrow
layout controls, keyboard examples, live regions, and console/resource checks.
You will also need to configure a Forgejo webhook in the repository settings
with the target URL https://fiduswriter.pages.fiduswriter.org/fwtoolkit and branch
filter pages.
npm install
npm run build
npm testBefore adding or changing a public component:
- Define narrow options and callback types; keep provider and application state in the host.
- Document initialization, repeated initialization, promise settlement where applicable, and teardown.
- Escape untrusted text and attributes; localize library-authored labels with
gettext(). - Cover keyboard operation, focus order/restoration, state changes, cleanup,
and hostile text in Jest tests. Reuse
test/helpers.tsfor keyboard, live region, and asynchronous assertions. - Keep styles in a component sheet, regenerate the bundle and scoped CSS, and
verify both staged CSS paths with
npm test. - Use the component demo template to check light/dark themes, scoped CSS, narrow viewports, reduced motion, and console/network cleanliness.
- Exercise the component in a real browser and at least one consumer before calling the migration complete.
src/— TypeScript sourcedist/— compiled JavaScript and declaration files (generated bynpm run build)css/— component styles and a minimalcolors.cssdemo/— Forgejo Pages demo sitetest/— Jest tests
"Fidus Writer" is a registered EU trademark of Lund Info AB. This repository's license covers the code, not the name and logo — see TRADEMARK.md and the Fidus Writer trademark policy.