Skip to content
fiduswriterPublic

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

fwtoolkit

fwtoolkit logo

Fidus Writer Toolkit — reusable TypeScript utilities, UI helpers and styles originally written for Fidus Writer but usable in any browser project.

JavaScript usage

import {escapeText, addAlert} from "fwtoolkit"
import {convertDataURIToBlob} from "fwtoolkit/blob"

TypeScript

The source is written in TypeScript and ships with declaration files:

import {Dialog} from "fwtoolkit/dialog"

CSS

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.

Design tokens

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-secondary is darkened to #656565 so secondary text still passes AA on --fw-surface-2; the mock's lighter #848383 is available as --fw-text-tertiary for large/decorative text only.

Floating-label fields

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.

Focus containment

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 listeners
  • modal: false sets and restores focus without trapping it.
  • Repeating activate() or deactivate() is safe; an instance can be reused.
  • restoreFocus: false leaves focus where it is when the scope closes.
  • getPortals may return focusable overlay elements rendered outside element, such as menus or tooltips, so modal isolation does not hide them.
  • onStackChange runs 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 tabindex is restored on deactivation.
  • FocusScope has no stylesheet requirement. The host remains responsible for dialog semantics, visible focus styling, Escape handling, and dismissal.

Accessibility

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.

Component APIs

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

Lifecycle and callbacks

  • Field and navigation constructors mount into the supplied dom element or expose an element for the host to append. Call destroy() 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, and destroy() settle the active session. Calling init() 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.

Dialog preset

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.

Provider-neutral settings

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.”

Host-owned export registry

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.

Toolbars and ordering

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.

Utilities

  • saveFile(data, options?) and saveBlob(blob, options?) preserve MIME data, prefer a user-chosen location when available, and report cancellation as a normal result.
  • ClipboardHelper copies text or HTML with a fallback and injected notification callbacks.
  • waitForElement supports explicit timeout and abort signals.
  • runWithProgress adapts promise-based work to ProgressTask, propagates progress/cancellation, and guarantees cleanup.
  • OneTimeCodeField clears completed codes synchronously and never logs or retains them.

ProseMirror subpath

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.

Demos

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.sh

For 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-build

Copy 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.

Development

npm install
npm run build
npm test

Component checklist

Before adding or changing a public component:

  1. Define narrow options and callback types; keep provider and application state in the host.
  2. Document initialization, repeated initialization, promise settlement where applicable, and teardown.
  3. Escape untrusted text and attributes; localize library-authored labels with gettext().
  4. Cover keyboard operation, focus order/restoration, state changes, cleanup, and hostile text in Jest tests. Reuse test/helpers.ts for keyboard, live region, and asynchronous assertions.
  5. Keep styles in a component sheet, regenerate the bundle and scoped CSS, and verify both staged CSS paths with npm test.
  6. Use the component demo template to check light/dark themes, scoped CSS, narrow viewports, reduced motion, and console/network cleanliness.
  7. Exercise the component in a real browser and at least one consumer before calling the migration complete.

Contents

  • src/ — TypeScript source
  • dist/ — compiled JavaScript and declaration files (generated by npm run build)
  • css/ — component styles and a minimal colors.css
  • demo/ — Forgejo Pages demo site
  • test/ — Jest tests

Trademark

"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.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages