8000 GitHub - zeyos/zx: Zx UI Library · GitHub
[go: up one dir, main page]

Skip to content
zeyosPublic

About

Zx UI Library

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

Xenon Design System (Zx)

Xenon is a dependency-free design system for browser applications; Zx is its vanilla-JavaScript implementation. It combines foundations, accessible components, repeatable workflow patterns, and application layouts in plain ES2022 modules. Source modules run directly in a browser; the distribution also provides ESM and classic-script bundles. Xenon originated at ZeyOS, while its components and contracts remain product- and framework-agnostic.

Coding agents start with docs/llms-small.txt — how every component works, the layout and the component for each job, and what never to build, in under 8k tokens — then read one component's file in docs/components/. docs/llms.md is the complete reference; all three ship in the package.

Quick start

Use the ESM bundle when the application already uses modules:

<link rel="stylesheet" href="/assets/zx.css">
<div id="notifications"></div>

<script type="module">
  import { Toggle } from '/assets/zx.esm.js';

  const toggle = new Toggle(null, {
    label: 'Notifications',
    value: 'enabled',
    onchange: (event) => console.log(event.detail.checked)
  });
  document.querySelector('#notifications').append(toggle.toElement());
</script>

For an application built from classic scripts, the IIFE bundle exposes the same API as window.zx:

<link rel="stylesheet" href="/assets/zx.css">
<script src="/assets/zx.global.js"></script>
<script>
  const toggle = new zx.Toggle(null, { label: 'Notifications' });
  document.body.append(toggle.toElement());
</script>

Import a component source module directly when a bundler needs the narrowest possible graph:

import { Slider } from '@zeyos/zx/src/components/slider/slider.js';

The package also exposes the bundled ESM entry for ordinary named imports. A bundler drops what an application does not import from it, apart from what the entry's Field-adapter registrations keep, so the per-component import is the smallest: measured with esbuild 0.28.1, Slider and Toggle bundle to about 49 kB minified from their own files and about 276 kB from the package entry. The core modules are importable the same way (@zeyos/zx/src/core/i18n.js, @zeyos/zx/src/core/icons.js), and zx-css does the same for the stylesheet.

TypeScript definitions ship with the package. They are generated from the JSDoc that documents every option, method, and event, so new Slider(null, { … }) is checked against SliderOptions and an unknown option or a wrong literal is an error in the editor. There is no TypeScript in the library itself and no compile step for consumers who do not want one.

Components accept an existing element or selector as their first argument. Passing null makes the component create and own its root. Call destroy() when a component is no longer needed; an owned root is removed, while an enhanced target is restored.

Optional integration requirements

Zx has no package runtime dependencies and its source modules import no external runtime packages. Optional integrations still need application-provided assets or clients. Chart draws through an adapter: the built-in SvgChartAdapter draws bar, line, pie and doughnut charts as SVG with nothing else loaded, and Surface draws its chart nodes with it by default; ChartJsAdapter draws any Chart.js 4 type with a Chart.js the host supplies. Chart.js 4.5.1 is pinned as a development dependency and copied to the documentation site's self-hosted vendor assets during its build; it is not bundled into Zx. Core icons use bundled SVG by default. Opting into Font Awesome requires host-loaded CSS or a kit. ZeyOS moduleIcon(), moduleChip(), and zeyosAppIcon() default to glyphs from the external custom ZeyOS Font Awesome kit; standard: true still needs stock Font Awesome assets. ZeyOS.connect() requires an injected compatible client and never imports the client package.

Component index

The groups match the demo sidebar.

Core

API Description
Component Lifecycle, event, element-registry, and cleanup base class.
defineElements() Registers the light-DOM <zx-*> wrappers for the supported declarative components.
h(), icon() Safe DOM and icon factories used by applications and custom renderers.
loadFontAwesome() Opts the icon layer into a Font Awesome kit; useBuiltinIcons() switches back.
onBreakpoint() Named width bands, observed on an element or the window.

The public core also includes HTTP helpers, i18n, date formatting/parsing, positioning, keyboard helpers, and small dependency-free utilities; see the named exports in src/index.js. Alongside them are locale-aware formatters (formatNumber, formatCurrency, formatPercent, formatFileSize, formatRelativeTime), collection helpers (groupBy, sortBy, uniqueBy), throttle beside debounce, escapeRegExp and highlightMatch for filtering lists, a namespaced storage() view that degrades to memory when the browser refuses writes, and toCsv/downloadBlob/copyToClipboard for exporting what a table is showing.

icon() renders the inline SVG glyphs Zx bundles — no webfont, stylesheet, or network request. They are outline icons from Lucide (ISC licence; the notice ships in src/core/icons.js): currentColor strokes on a 24-unit grid, about 1.2px at the default 16px. registerIcons() adds more, either filled ([viewBox, path], e.g. Font Awesome paths) or outlined ([viewBox, path, 'stroke'], e.g. further Lucide icons). Applications that want Font Awesome call loadFontAwesome({ kit }) once, and every icon in the library follows, including names Zx maps to their Font Awesome counterparts. Names can also pick a renderer themselves: 'fa:user', 'duotone:user', 'kit:zeyos-notes', 'builtin:check', or a literal 'fa-solid fa-user' class list. ZeyOS module icons and their identity colours live in the ZeyOS binding — see src/zeyos/modules.js.

Inputs

API Description
button(), buttonGroup() Styled native button and grouped-button factories.
badge(), badgeGroup() Status pills with semantic kinds, variants, and sizes; with a tone, a categorical tag.
kbd() Keycaps for every shortcut hint, with platform glyphs for Mod and the named keys.
CheckButton Two-state pressed button with optional state-specific labels.
Toggle Native-button switch with a 8000 separate submitted value.
Search Search input with debounced input, submit, and clear events.
Select APG combobox with local or async filtering, pinned items, locale/country/priority/status/permission presets, and an optional ZeyOS entity picker. Select.locale() and Select.country() return ordinary Select instances; Select.localeItems() and Select.countryItems() generate rows without DOM.
Checklist Searchable checkbox group with optional async loading.
TagPicker Multi-select combobox that keeps its selection as removable tags.
NumberField APG spinbutton with step buttons, ranges, units, and wrapping.
Rating Star rating as a radio group, with optional half steps.
Slider Range control for a bounded numeric value, with marks and an optional number box.
DatePicker APG calendar grid with bounds, week numbers, and optional time selection.
MonthPicker Twelve-month grid with year navigation.
TimePicker Segmented local-time picker.
Datebox, DateTimeBox Formatted date input and its date-time factory variant; displayFormat shows a screen's own date format while the field is not focused.
DateRangePicker Two-month range calendar with presets, night bounds, and range preview.
DateRangeBox Formatted date-range input with an anchored range calendar.
Timebox Segmented signed or unsigned duration input.
copyButton() Button that copies a string and confirms it in place.
CopyInput Read-only box holding a value to be copied, with the copy button attached.

Overlays

API Description
Message Inline messages, floating toasts, and progress status.
Modal Minimal native-dialog overlay with light-dismiss support.
Dialog Titled modal with buttons, named views, alert, confirm, and prompt helpers.
Dropdown Generic anchored popover with placement fallback.
MenuButton APG menu button built on Dropdown.
ContextMenu APG right-click menu for a region or, via selector, per row.
Sheet Dockable panel that can float as a modal or nonmodal dialog.
SheetStack Ordered group of Sheets read as one drill-down, stacked or cascaded side by side.
Tooltip, tooltip(), describe() Hover/focus description bubble anchored with position().

Data

API Description
EntityRef Dense linked/static entity identity with labelled metadata and injected actions.
FileItem, FileList Durable and transient file presentation with MIME/size metadata, status, progress, downloads, and collection states.
ActivityItem, ActivityList Chronological activity entries and grouped collections with actor, time, attachment, action, loading, and empty slots.
Table Sortable/selectable table with typed transaction columns, flat-data hierarchy/treegrid projection, and opt-in cell/row editing.
RecordView Shared record collection state for table, card, and Kanban views.
TableView Record-oriented Table composition with shared fields, portable state, column visibility/order, sorting, and selection.
CardView Responsive record cards with configurable fields, safe preview media, grouping, actions, sorting, and selection.
KanbanView Record board with configurable columns, swim lanes, WIP guidance, and cancelable pointer/keyboard movement.
Grid, Grid.BillingItems() Table-compatible preset surface with editable currencies, units, totals, and sub-items.
Chart, SvgChartAdapter, ChartJsAdapter Accessible chart host; SvgChartAdapter draws bar, line, pie and doughnut charts with no dependency, ChartJsAdapter any Chart.js type with host-provided Chart.js 4.
Calendar Agenda/day/week/month/year scheduling with timed collisions, spanning events, range selection, and configurable optimistic drag/resize editing.
Filter Nested, backend-neutral filter expression editor.
DataFilter Declarative select, text, and custom filters for client-side row sets.
FilterPanel Typed filter form built from a server's own field metadata, drafted then applied.
SortControl Searchable sort field and direction control.
ViewSettings Portable field visibility, order, grouping, and view settings.
ListToolbar Search, result count, view switch, and badged tools above a record view.
TreeView APG tree with lazy children, filtering, tri-state checkboxes, and hover-revealed rowActions.
Finder Miller-columns hierarchy browser with an optional preview pane.
Pagination Page, page-size, and load-more pager, with the pure paginationRange() helper.

Forms

API Description
Field Label, description, validation state, and adapter-backed form control.
Fieldset Native fieldset that owns and coordinates fields.
Form Form composition, values, validation, highlighting, and actions.
CodeEditor Text-safe structured-text/source editor with native undo, Tab indentation, and position feedback.
Questionnaire Guided one-question-at-a-time flow: branching, path-aware progress, review.
ValueList Validated, sortable tag/chip editor.
MultiValueEditor Ordered editable rows with add, remove, and move controls.
FieldUpload Click/drop file upload with progress, abort, validation, and preview.

Layout

API Description
AccountMenu Identity trigger and grouped account actions over MenuButton.
AppIcon, zeyosAppIcon(), moduleChip() White-glyph identity surface: a generic tile core, circular ZeyOS application presets, compact module/entity tiles, module colour, badges, selection, and CSS-first material.
Avatar Fixed-size user image with initials fallback and optional presence.
Groupbox Collapsible section backed by native <details>.
Card Semantic content/record surface with media, native title link, actions, and footer.
StatTile, statTile() Labelled metric with optional delta, sparkline, and loading state; variant: 'plain' sets the figure on the page, and emphasis lets one figure lead.
Aurora One- to four-colour ambient canvas light; chrome, raised content, and overlays respond through shared material tokens.
Launcher Cmd/Ctrl+K application and record launcher with ranked local items and abortable grouped sources.
Panel Framed, optionally collapsible section with a footer.
MasterPanel Full-height application panel with fixed header actions and footer.
Tabbox APG tabs in four appearances, with lazy content, closing, badges, and disabled states.
NavigationBar Responsive application navigation with optional tab panels and overflow.
AppSidebar Expanded or minimized vertical application navigation plus horizontal rails; descendants are inline only while expanded. Sections group a tree; layout: 'modules' puts a module strip beside one module's menu.
ModuleBar Colour-coded module tiles in a strip or bar: flyout menus, live badges, one Tab stop, and an "All modules" catalogue for what does not fit.
Toolbar APG toolbar: one tab stop, arrow-key movement, and overflow into a menu.
Dock Resizable, collapsible pane layout with tabs and hosted Sheets.
WorkspaceSwitcher Workspace identity and switching menu.
SplitView Resizable two-pane split with a keyboard-operable separator.
Stepper Linear multi-step progress with completed, active, and error states.
Breadcrumb Hierarchy trail with middle-collapse, pairing with Finder and TreeView.
emptyState() Placeholder for an empty list, table, or panel, with optional actions.
stack(), grid(), aspect() Spacing, an intrinsically reflowing grid, and a fixed-ratio box.
spinner() Indeterminate activity ring for a wait of unknown length.
ProgressBar Determinate progress track, with success and error states.
InlineLoading Status line that resolves a wait into its outcome in place.
skeleton(), skeletonText(), skeletonTable() Placeholders shaped like the content that is coming.
truncate() Clamps text to a number of lines, with the full value on hover.

Agents

API Description
AgentThread Accessible conversation feed with streamed answers, versions, and actions.
AgentAvatar Generated agent face — a coloured geometric shape with eyes — that shows its activity.
BlockView, renderBlocks() Safe structured answer content with incremental streaming.
Composer Message input with attachments, mentions, commands, context, and queued messages.
RunTrace Tool calls, reasoning summaries, retries, and handoffs within a run.
RunStatus Run state, steps, elapsed work, tokens, and cost.
ApprovalCard Application-controlled approval, editing, rejection, and typed confirmation.
SourceList Citations and source metadata without loading remote content.
PromptStarters Suggested conversation starters that report a selection.
Surface Validated agent-authored forms, tables, choices, and reviews with one reply.

See the Surface guide and component catalogue for supported schemas and streaming helpers. Both ship in the package.

Composing surfaces at runtime

An agent can put interface in front of a person without writing HTML: the model composes a surface/1 document, and Surface (or openSurface()) validates it and draws it with Zx components. The server gives the model its tools and guide from the catalogue, which imports nothing that needs a browser:

import { CATALOG, surfacePrompt, surfaceTools } from '@zeyos/zx/src/components/surface/catalog.js';

const tools = surfaceTools(CATALOG, { profile: 'answer' });    // show_surface only
const guide = surfacePrompt(CATALOG, { profile: 'answer' });   // the nodes it may use, and when
  • Profiles — answer shows (prose, figures, tables, charts, records, links, layout), ask adds forms, choices and confirmations, review adds proposed changes, and full is everything. Give the model the narrowest that does the job: answer costs less than half of full. narrowCatalog(CATALOG, { profile, intents, nodes }) narrows further.
  • One reply per surface — every surface ends in exactly one reply/1, also when the person closes it or it is replaced. Wait for it, and treat it as the person's answer, not as proof that anything happened: the server runs its own policy again before it acts.
  • Errors go back to the model — what fails validation is dropped and reported (the error event, getErrors(), or validateDocument() from surface/validate.js on the server); return those errors to the model so it can correct the surface and send it again.

Start from a layout

The layout gallery holds complete, working screens on one shared application shell, each with its source. Start a new screen from the closest one and change the data and the copy, rather than composing components on a blank page: the columns, toolbar, drawers, states, and keyboard map come with it.

  • Templates — complete applications: mail, issue-tracker, wiki, ai-chat, agent-workspace, invoice-editor, item-inventory, workflows, infrastructure, crm.
  • Patterns — single screens: master-detail, record-collection (any list of records as a table, list, cards, gallery, or board), dashboard, inbox, record-page, agent-chat, agent-canvas, record-wizard, checkout-wizard, settings-workspace, system-states, zeyos-invoices.

layouts.html#<id> opens one; layout.html#<id> shows it alone. The shell helpers (layouts/kit.js, kit.css) and the record-screen composition (createOverview() in layouts/overview.js, overview.css) are served beside the layouts and are meant to be copied into an application. The agent reference (docs/llms.md, "Choosing what to build with") maps every screen to a layout and every job to a component.

Talking to ZeyOS

Use @zeyos/client for ZeyOS authentication, transport, generated resource operations, and runtime schema introspection. Zx adds zx-zeyos, a schema-driven layer above that client: inject an existing client into connect, zeyosTable, zeyosView, zeyosForm, or zeyosSelect to generate typed record views, tables, forms, and async entity selectors from real resource metadata.

import { createZeyosClient } from '@zeyos/client';
import { zeyosForm, zeyosTable } from '/assets/zx-zeyos.esm.js';

const client = createZeyosClient({ platform, auth });
const list = zeyosTable(client, 'transactions', {
  fields: ['transactionnum', 'account', 'date', 'netamount', 'status']
});
await list.load();

const editor = zeyosForm(client, 'transactions', {
  fields: ['transactionnum', 'account', 'date', 'netamount', 'status']
});

zeyosView() can coordinate named Table, Card, and Kanban configurations through SavedViewRegistry. Saved documents are isolated by exact userId + workspaceId + resource, keep records and selection out of persistence, and use an injected atomic transport. Existing ZeyOS installations can adapt their authenticated fields, fields_save, and fields_remove endpoints with createLegacySavedViewTransport(); the client-provided user id is never sent as authority.

The injection design means Zx never imports or bundles @zeyos/client. The optional binding ships separately as dist/zx-zeyos.esm.js and is not part of the root src/index.js API. See the schema-driven website/layouts/zeyos-invoices.layout.js for list, filter, sort, edit, and create wiring.

The same entry point carries ZeyOS module identity — the icon and colour of every module, keyed by module, entity, or API resource name:

import { moduleChip, moduleColor, useZeyosIcons } from '/assets/zx-zeyos.esm.js';

await useZeyosIcons();                        // loads the ZeyOS Font Awesome kit
nav.append(moduleChip('tickets', { size: 24, title: true }));
moduleColor('invoices');                      // '#535494'

src/zeyos/modules.js is the configuration file behind it: one entry per module with its kit icon name, identity colour, label, and a stock Font Awesome fallback. The --zx-module-* CSS custom properties are ge A2FE nerated from that file, so CSS and JavaScript cannot disagree about a colour.

Themes

Load zx.css once. Zx components consume semantic --zx-* tokens and inherit their values from the document. Select a built-in theme on any ancestor (normally <html>):

<html data-zx-theme="dark">

Top-layer menus, dialogs, tooltips, launchers, and toast regions stay under the nearest Zx theme scope in the DOM, so a theme or product-token override on a nested application shell also applies to its overlays. Pass the optional scope context to Modal, Dialog, Sheet, Launcher, or static Message calls when the opener is not inside the intended scope.

Theme values are light, dark, and auto. auto follows the operating-system color preference.

There is one geometry. Spacing steps are multiples of --zx-space-unit (4px: 4, 8, 12, 16, 20, 24, 32, 40), radius steps are fractions of --zx-radius (4px: 2, 3, 4, 6), and controls are --zx-control-height (30px) tall. To tighten or loosen an application — or one region of it — override those tokens rather than switching a mode:

:root {
  --zx-space-unit: 3.5px;
  --zx-control-height: 28px;
}

Data rows follow the control height through --zx-row-height (36px by default), and type is one base, --zx-text-base (14px), with every --zx-text-* step derived from it. Authored content — a document, a record's notes, a message — takes a second, separate register: wrap it in .zx-prose and it reads --zx-font-prose, --zx-prose-size, --zx-prose-leading and --zx-prose-measure, so a product can set its documents in a serif without touching a control. .zx-callout sets a paragraph apart, neutral unless it is a status or a category.

A second attribute picks the accent, orthogonally to the theme:

<html data-zx-theme="dark" data-zx-preset="ocean">

Seven presets ship — zx (the ZeyOS green, and the default), zeyos, ocean, violet, rose, slate, folio. Each is five declarations of the tier-1 accent ramp that the semantic tier resolves through, so a preset rethemes light, dark, and auto at once:

[data-zx-preset="acme"] {
  --zx-accent-300: #c4b4ff;
  --zx-accent-400: #a684ff;
  --zx-accent-500: #8e51ff;
  --zx-accent-600: #7f22fe;
  --zx-accent-700: #7008e7;
}

Light surfaces take the 600 and 700 stops, dark ones take 300, 400, and 500 — so keep 600 legible against white and 400 against near-black, and --zx-color-on-accent stays correct in both. The primary button is the exception on purpose: --zx-color-accent-solid is the 600 stop with white ink in both themes, so the one solid accent on a screen never turns into a bright slab in dark. The theme studio renders every component family under a live theme and exports the result.

The studio's Material is how surfaces answer light — Glass (the default, a thin lit pane), Deep glass, Frost (milk glass), Smoke (tinted glass), Paper, Satin and Enamel (opaque: matte, brushed or glazed, no blur), or Flat. Each is a set of token overrides composed from six per-theme ingredients (--zx-color-glass-rim, -ring, -lift, -shade, -edge, -tint), so one recipe serves light and dark, and reduced-transparency, high-contrast and forced-colour settings restore solid surfaces on their own.

Anything beyond the accent is a semantic token override, without reaching into component CSS. Declare it once on :root, as light-dark(<light>, <dark>) where the two appearances differ: a theme attribute only picks which half a region reads, so the override reaches light, dark, auto, and nested regions alike, and the roles derived from it follow.

:root {
  --zx-color-bg-page: light-dark(#f4f1eb, #1a1815);
  --zx-color-bg-surface: light-dark(#fffdf8, #22201c);
  --zx-color-text: light-dark(#26221d, #ece6dc);
  --zx-color-text-muted: light-dark(#655e54, #a89f92);
}

Prefer semantic tokens such as --zx-color-*, --zx-control-*, --zx-space-*, --zx-radius-*, and --zx-text-*. Palette tokens are implementation details and should not be used by application or component CSS. A few roles carry most of the visual language:

  • --zx-color-bg-chrome for navigation and inspector columns beside the --zx-color-bg-surface canvas, and --zx-color-border-subtle for dividers inside them — tone separates, lines only where tone cannot.
  • --zx-color-bg-current (neutral) for where you are, --zx-color-bg-selected (accent tint) for what you picked.
  • --zx-color-text-muted for secondary text and --zx-color-text-subtle for icons and meta.
  • --zx-color-tone-<hue>-bg / -fg (blue, teal, green, amber, orange, red, pink, violet, slate) for categorical colour — tags, avatars, icon tiles — and --zx-color-chart-1 … -8 for chart series. Neither is the accent or a status colour; success is a yellow-green of its own.

Add data-zx-fields="quiet" to a property panel and its native fields show no border or fill until hovered or focused.

Browser support

Zx targets current evergreen Chrome, Edge, Firefox, and Safari with browser capabilities from roughly 2023 onward. It uses native <dialog>, the Popover API, :has(), container queries, ES2022 modules, and abortable event listeners. No transpilation or legacy-browser polyfill bundle is provided. CSS anchor positioning is used only when supported; the library otherwise uses its JavaScript positioning fallback.

Development

Install the development toolchain and start the no-build demo server:

npm ci
npm run serve

Open http://127.0.0.1:8321/website/docs.html for the documentation — getting started, and every component with a live demo and its JavaScript source — and http://127.0.0.1:8321/website/layouts.html for the gallery of application layouts. Also available: http://127.0.0.1:8321/tests/smoke/smoke.html for source-module smoke tests, or build first and open http://127.0.0.1:8321/tests/smoke/smoke-dist.html for classic-script distribution tests.

npm test           # Node unit tests plus semantic-token lint
npm run build      # writes ESM, ZeyOS, global, CSS, and declaration assets to dist/
npm run build:site # assembles the deployable documentation site into site/
npm run serve:site # serves site/ exactly as it will be deployed

Browser checks use an already-installed Chrome. Set ZX_BROWSER_CHANNEL to another installed Playwright browser channel, or ZX_BROWSER_EXECUTABLE_PATH to an executable path; use one option at a time. No browser is downloaded by the checks.

The checked-in ZeyOS client asset has a source and checksum manifest. To refresh it from a local client checkout, run node tools/build-client-vendor.js --source /path/to/client; verify it with node tools/build-client-vendor.js --check. Ordinary site builds verify the asset without needing that checkout or a network connection.

Installing

npm install @zeyos/zx
import { Table, Message } from '@zeyos/zx';
import '@zeyos/zx/zx.css';

zx.css is the whole library. To load only what an application uses, zx-css writes one stylesheet for the components named: the tokens and base rules, then those components and everything they depend on, resolved from the source.

npx zx-css select table --out public/zx.css --min
npx zx-css select table --list   # the files it contains, in order

Additional entry points: @zeyos/zx/zeyos (the schema-driven ZeyOS binding) and @zeyos/zx/global for classic script tags. For styles, @zeyos/zx/zx.core.css is the tokens, base rules, icons and reading type, @zeyos/zx/src/components/select/select.css is one component's own rules, and @zeyos/zx/zx.layered.css puts the whole library in @layer zx, so that unlayered application rules win without a specificity fight, and so do unlayered resets and third-party stylesheets: docs/llms.md covers when to choose it.

ZeyOS module colours are optional: import @zeyos/zx/styles/zeyos.css when using the ZeyOS binding. The generic core and full-library stylesheets do not include that product palette.

The Locales guide covers the shipped English/German catalogues, adding application languages and regional variants, custom messages and variables, plural forms, formatting, and runtime language switching. Select.locale() and Select.country() return ordinary Select instances; selecting a locale is separate from installing its translations.

Documentation lives at https://zx.zeyos.com.

About

Zx UI Library

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

0