Skip to content

Latest commit

 

History

History
323 lines (246 loc) · 27.5 KB

ui-primitives.md

File metadata and controls

323 lines (246 loc) · 27.5 KB

UI primitives

Tabs, steppers, accordions, dialogs, drawers, popovers, tooltips, menus, toasts, galleries with a lightbox, carousels, rating inputs, input masks, signature pads and a searchable select work on their own or beside CanopyX data views. The runtime loads their versioned parts when a component is mounted. Serve the canopyx-ui-*.js and .css files beside the entry point, together with its other part files. CanopyHtmlAssets.WriteTo(...) writes that asset set from .NET.

Write a tab set from .NET

using CanopyX;
using CanopyX.Html;
using CanopyX.Html.Ui;

var tabs = new CanopyTabs("workspace", "Workspace sections");
tabs.Tabs.Add(new CanopyTab("overview", "Overview") {
    ContentHtml = "<p>Workspace summary.</p>"
});
tabs.Tabs.Add(new CanopyTab("activity", "Activity") {
    Badge = "12",
    BadgeTone = Tone.Warning,
    ContentHtml = "<p>Recent activity.</p>"
});

string fragment = tabs.ToHtmlFragment();
CanopyHtmlAssets.WriteTo("assets");

Include the runtime and its base stylesheet once in the page that contains fragment. Declarative components mount when the document loads. A host that inserts markup later calls CanopyX.mountUi(container) and awaits the returned controllers' ready promises. Part markup in that insertion registers only where the browser runs its scripts: parsed with the page, or inserted with Range.createContextualFragment. Markup set through innerHTML never runs them, so the runtime loads the parts from their files beside it, which the host then serves (see part stylesheets).

Declare the CanopyUiKind values for the whole single-file page, including deferred sections and regions the host inserts later. Use CanopyUiKind.Toasts for CanopyX.notify, CanopyUiKind.Dialog for confirmations opened by script, and CanopyUiKind.Drawer for drawers opened by script. The writer uses CanopyHtmlOptions.UiComponents to include the corresponding parts and their dependencies. An inline standalone page registers those parts before running HeadHtml.

var options = new CanopyHtmlOptions {
    UiComponents = { CanopyUiKind.Toasts, CanopyUiKind.Dialog, CanopyUiKind.Drawer, CanopyUiKind.Gallery }
};

When assembling the page yourself, pass the same kinds to CanopyHtmlAssets.GetRequiredUiParts and embed the returned parts once, or supply them through the host part loader.

C# kind data-cx- suffix Owning part
Dialog, Drawer, Popover, Tooltip dialog, drawer, popover, tooltip ui-overlays
Menu menu ui-menu
Tabs, Stepper, Accordion tabs, stepper, accordion ui-tabs, ui-stepper, ui-accordion
Toasts toasts ui-toasts
Gallery, MaskedInput, Signature lightbox, mask, signature ui-lightbox, ui-mask, ui-signature
Carousel, Rating, Select carousel, rating, select ui-carousel, ui-rating, ui-select

The builders encode identities, labels, badges and accessibility references. Properties named ContentHtml or FooterHtml contain trusted host HTML; encode or sanitize untrusted content before assigning them. Without JavaScript, tab and step panels remain readable with headings. Overlay builders emit their closed content and a separate ToTriggerHtmlFragment(label) button.

The ui-primitives.html example embeds the required parts with GetRequiredUiParts. Each part registers as its script runs and installs when a component first needs it. Use GetMarkup(nonce) for a page protected by a nonce-based Content Security Policy, or serve the part files beside the runtime for a policy of script-src 'self'; style-src 'self' (see security).

Configure behavior in JavaScript

The UI, tree, grid and reporting entry points expose the same UI factories. The slim flow entry point contains forms and flows; use a grid entry point for a page combining flows and these UI controls. Each factory returns a stable controller immediately; ready resolves after its part and dependencies have loaded. Calls made before readiness wait for initialization.

const sections = CanopyX.tabs('#workspace', {
  hash: true,
  beforeChange: async (from, to, signal) => {
    return await confirmSectionChange(from?.id, to.id, signal);
  }
});

await sections.ready;
await sections.select('activity');
// When the host removes this part of its page:
sections.destroy();

setBadge(id, badge) changes a tab's badge as counts change: text, a number (formatted in the page language) or null to remove it. It updates the tab, its panel heading and the More and phone pickers, and the tab's accessible name follows. A third argument sets the badge's tone (neutral, info, success, warning, danger, muted, or a host tone the page styles through data-tone); null removes it, and leaving it out keeps it. CanopyTab.BadgeTone sets the first tone in .NET. Built-in tones use the theme's status colours in light and dark, and a badge without a tone keeps the accent.

sections.setBadge('activity', 14);
sections.setBadge('activity', 3, 'danger');
sections.setBadge('activity', null);

Tabs support underline, pills, segmented and vertical styles; scroll, More and pill-wrap overflow; justified equal-width tabs; deferred panels; hash state (#<id>=<tab>, beside a plain anchor and other sets in the same fragment, keeping history.state); remember, which keeps the selected tab in localStorage; next() and back(); and optional automatic progression with a visible Pause/Play control. A deferred loader receives the destination record and an AbortSignal. New navigation cancels stale guards and loaders. keepAlive: false reloads deferred content after leaving it.

Automatic tab progression

const sections = CanopyX.tabs('#workspace', {
  autoProgress: { interval: 5000, pauseOnHover: true, pauseOnFocus: true }
});
await sections.ready;

interval is a positive number of milliseconds. Both pause options default to true. Progression waits for the initial panel, skips disabled tabs, and wraps after the last enabled tab. Each interval starts after the previous selection and its deferred content settle. A rejected change pauses progression. Hover, focus and a hidden document suspend the timer without catching up later.

The visible, keyboard-accessible Pause/Play button gives readers control over automatic updates as required by WCAG 2.2.2. Selecting a tab by click, keyboard, picker, swipe, hash navigation or the controller stops progression, including attempts to select the current or a disabled tab. Leaving hover or focus does not restart a stopped timer; Play explicitly starts a fresh interval. Pause cancels a pending automatic selection without taking ownership of manual navigation.

Reduced motion disables automatic selection and the animated progress fill. Play remains disabled, with a localized explanation. Changing to reduced motion cancels a pending automatic guard or loader. Changing back leaves progression paused until Play. Manual navigation remains available. The built-in locale packs supply tabsPause, tabsPlay and tabsMotionDisabled; pass a locale's labels or override those keys in the component's labels option.

The .NET builder emits the same settings as declarative attributes:

var tabs = new CanopyTabs("workspace", "Workspace sections", new CanopyTabsOptions {
    AutoProgress = new CanopyTabsAutoProgress {
        Interval = 5000,
        PauseOnHover = true,
        PauseOnFocus = true
    }
});
tabs.Tabs.Add(new CanopyTab("overview", "Overview") { ContentHtml = "<p>Summary.</p>" });
tabs.Tabs.Add(new CanopyTab("activity", "Activity") { ContentHtml = "<p>Recent activity.</p>" });
string fragment = tabs.ToHtmlFragment();

AutoProgress defaults to null (off); a new settings object defaults to a 5000 ms interval. JavaScript autoProgress replaces the declarative settings, and autoProgress: false disables them. Before 1.0, replace autoAdvance with autoProgress and remove loop; progression wraps through enabled tabs. No compatibility alias is provided.

CanopyX.stepper(root, options) adds guarded steps, optional skipping, validation, drafts and finish callbacks. A validation callback returns false or a list of messages to keep the current step open. Messages appear in a focused alert and are linked to invalid fields. Report and static stepper modes remain script-free. Tabs and interactive steppers share the same phone picker, preserving badges and counts. Tabs measure their labels, icons and badges before collapsing, with an eight-pixel resize margin to prevent repeated switching near the boundary. Menu overflow keeps at least three visible choices plus More while they fit. Interactive steppers use the picker below a container width of 640 px.

The stepper's Back, Skip, Next and Finish toolbar sits under the panels by default. CanopyStepperOptions.ToolbarPosition moves it above them (Top) or repeats it above and below (Both), and ToolbarHtml adds trusted host controls, such as a Help link or a Cancel button, before the step actions in each toolbar (with ShowFooter). The host handles their clicks.

CanopyStep.Badge puts a badge beside the step's label and in its panel heading, such as a count of items to review. Like a tab badge it is part of the step's accessible name ("Review 3"), and CanopyStep.BadgeTone colours it with the same tones. The phone picker shows it when the step has no status of its own.

Show sections with an accordion

var help = new CanopyAccordion("help", new CanopyAccordionOptions { Search = true });
help.Items.Add(new CanopyAccordionItem("start", "Getting started") {
    Open = true,
    ContentHtml = "<p>Create a workspace.</p>"
});
help.Items.Add(new CanopyAccordionItem("billing", "Billing") {
    Disabled = true,
    ContentHtml = "<p>Ask your administrator.</p>"
});
string fragment = help.ToHtmlFragment();

Every section stays open and readable until the runtime is ready, so a page without JavaScript shows all of its content under its headings. Multiple keeps several sections open; otherwise opening a section closes the open one, and the last one can still be closed. HeadingLevel fits the headings into the page's outline. Style chooses a bordered, flush, separated or section look, and Indicator and IndicatorPosition choose a chevron or plus on either side. Panels are region landmarks in an accordion of up to six sections, as the ARIA pattern advises. Badge adds a badge to a section's heading, and BadgeTone colours it with the same tones as a tab badge.

const help = CanopyX.accordion('#help', {
  multiple: true,
  hash: true,
  remember: 'help-page',
  sections: [{ id: 'usage', loader: (item, signal) => fetch('/usage', { signal }).then(response => response.text()) }]
});
await help.ready;
await help.open('usage');
help.getOpen();      // ['start', 'usage']
help.filter('usage or "getting started" -archived');
  • Open state. hash writes open sections to the address (#help=start&help=usage) and follows Back and Forward; remember keeps them in localStorage under canopyx:accordion:<key>. A link wins over remembered state, and remembered state over open and the markup. A disabled section keeps its markup state.
  • Deferred content. A template in a panel, deferred: true or a loader defers it, as in tabs. In a multiple accordion each section loads on its own, so opening one never cancels another. Closing a section aborts its pending loader, and opening it again loads afresh; keepAlive: false also disposes loaded content when it closes.
  • Guards and events. beforeChange(from, to, signal) can refuse a change: to.open is the requested state, and in a single-open accordion from is the section that would close. The root fires cancelable cx-accordion:beforechange, then cx-accordion:change ({ item, open, source }), cx-accordion:load and cx-accordion:error. These events bubble, so a nested accordion's reach its parent; compare event.target.
  • Filter. search adds a filter box, filter(query) drives it from the host, and Escape clears it. It reads each section's header, including badges and actions, and understands or or |, quoted phrases and a leading - or !. Filtering hides sections without closing them, so clearing it restores what was open.
  • Header actions. ActionsHtml places links and buttons beside the heading, never inside its button, so they keep their own clicks and the heading stays a valid control. CopyTitle adds a button that copies the section title.
  • Content. A grid or tree in a closed section stays unrendered until the section opens, and then sizes to its panel. MountWhenVisible also postpones parsing it. Mount a fragment that a loader returned from cx-accordion:load with CanopyX.mount(event.detail.panel).
  • Nesting. A section can hold another accordion. Each one owns only its own headings, keys and single-open rule.

Open overlays

Use CanopyX.dialog, drawer, popover, tooltip and menu with their declarative roots. The returned controllers expose open, close, refresh and destroy as applicable. A trigger can come from the builder's data-cx-trigger reference or the trigger option.

Dialogs use the native modal dialog. Drawers are non-modal on desktop and become full-height modal sheets when their container narrows below 640 px. modal: true also makes a desktop drawer modal. The shared overlay manager handles nested Escape order, modal focus trapping, scroll locking, dismissal and focus return. Anchored overlays flip and shift within the viewport.

A close or cancel button (data-cx-close, data-cx-cancel) inside an overlay closes the nearest overlay around it, so a dialog or popover nested in a drawer closes alone. A data-cx-close that names an overlay by id closes that overlay instead, such as the drawer around a nested dialog or a sibling drawer; an id that names no overlay falls back to the nearest one. These are outside the contract:

  • Close buttons outside every overlay. A page toolbar's data-cx-close doesn't close the overlay it names; call the controller's close() from the button instead.

  • Presses outside the top overlay. A press outside the top overlay dismisses it as an outside press, also a press on a button that names another overlay. A close in a lower drawer that names the top drawer therefore closes it without its cancel event, so a host can't veto it. A press inside an overlay that lives in a shadow root reads as outside it.

  • Native cancel on an overlay that is not on top. requestClose() or a native cancel closes its overlay only when it is on top. On a drawer whose nested popover is on top it does nothing; Escape closes the top overlay.

  • Several controllers on one element. Mount one dialog, drawer or popover per element; with several, a close or cancel button closes the open one.

Confirm and submit

A dialog's typed actions replace hand-written footer markup. CanopyDialog.Confirm builds the common case: an alert dialog with a plain text question, a Cancel button it focuses first, and one answer.

var restart = CanopyDialog.Confirm("restart-spooler", "Restart service", "Restart the print spooler?",
    CanopyDialogAction.Submit("restart", "Restart", Tone.Danger, target: "/services/spooler/restart"));
restart.Fields["__RequestVerificationToken"] = antiforgeryToken;
var html = restart.ToTriggerHtmlFragment("Restart spooler") + restart.ToHtmlFragment();

Each CanopyDialogAction has a label, a tone and an optional target. Tone.Danger draws a destructive button, and every tone is written as data-tone for host themes. Choosing an action fires the cancelable cx-dialog:action event with detail.action. A host that cancels it answers itself, for example with fetch, and closes the dialog through its controller. Otherwise an action with a target submits the footer form with action=<id> and the dialog's Fields, once, and an action without one closes the dialog with the reason action. With a target, the buttons submit even before the runtime loads.

Show records in a drawer

A dialog or drawer's open(options) takes what it shows. Calling open on one that is already open keeps it open: it swaps the content and moves the focus return to the new record, with no close and reopen.

const reader = CanopyX.drawer('#evidence', {
  records: direction => showRecord(index + direction)
});

function showRecord(next, trigger) {
  index = next;
  reader.open({
    returnFocus: trigger,                       // Focus goes back here when the drawer closes.
    position: { current: index + 1, total: rows.length },
    history: { url: '?record=' + rows[index].id },
    loader: async signal => {
      const response = await fetch('/evidence/' + rows[index].id, { signal });
      if (!response.ok) throw new Error('The evidence could not be loaded');
      return await response.text();             // Trusted host HTML, or a Node.
    }
  });
}
  • Content. content (a Node, or HTML the host trusts) replaces the body at once; setContent(content) does the same without opening. loader(signal) marks the overlay aria-busy, shows a loading line, and replaces it with the result. A newer open aborts the previous loader's signal and ignores its late result. A failure shows its message with a Retry button; refresh() runs the current loader again. A loader factory option loads once, on the first opening. The root fires cx-drawer:load and cx-drawer:error (cx-dialog: for dialogs), and getState().loading tells whether a load is pending.
  • Records. With records, the drawer header shows Previous and Next buttons beside the close button, and Up and Down move between records when focus is outside a field. position: { current, total } adds the "2 of 14" label (the tabsPosition label) and marks the buttons disabled at the ends. The buttons use the drawerPrevious and drawerNext labels.
  • Address. history: { url } pushes the address on opening, so a link or reload can show the same record and Back closes the overlay; Forward opens it again. A record switch replaces that entry, and closing the overlay goes back. push: false replaces the current address and restores it on closing. Given as a factory option, history also opens the overlay when the page is loaded on that address; with base, the landing entry becomes base and the overlay's address is pushed above it, so Back stays on the page. Firefox adds no entry for a push made before the reader interacts with the page, so there Back from a landing leaves the page as it would without the overlay. The overlay marks its own entries with cxOverlay in history.state and keeps the rest of the state the host put there.

An overlay copies its host's resolved scheme and scoped design roles when moved outside that host. Its colors, typography, spacing, radii, elevation and motion consume --hfx-* roles with standalone fallbacks. Use data-theme="light" or "dark" on a standalone component, or supply roles from its parent. Component styles live in @layer hfx.components; a product layer can restyle public data-cx-part and data-state hooks.

Custom part selectors use data-cx-part. The C# builders style through tones (such as Tone.Danger on a dialog action) and the theme only: no variant names, classes or colours.

Embedding in an existing site

Component styles live in @layer hfx.components. Unlayered rules always beat layered ones, whatever their specificity, so a site's own element rules win over the components' rules for the same properties. A typical reset such as button { font: inherit; padding: .5em 1em; background: none } restyles every component button.

  • The overlay close button keeps its label hidden with an unlayered .cx-overlay-close { font-size: 0 }, so the label never prints beside the × glyph.
  • For other properties a site sets on bare elements (button, input, select, a, h2, ul), either scope those rules away from the components (:where(main) button:not([class^="cx-"])), put them in a layer declared before hfx.components (@layer site, hfx.components;), or restate the components' values in an unlayered rule of your own.
  • Tabs, menus and steppers restate font-family, font-size and color on their roots; padding, background, border and line height on their buttons come from the layer.

Add a context menu

const record = document.querySelector('#report-record');
const dispose = CanopyX.contextMenu(record, [
  { id: 'open', label: 'Open record' },
  { id: 'pin', label: 'Pin record', kind: 'checkbox', checked: false }
], {
  onSelect(item) {
    handleRecordAction(item.id, record, item.checked);
  }
});

await dispose.ready;
// Remove listeners, timers and any open menu:
dispose();

A selector delegates to matching elements; an element binds directly. The factory receives the opening event and matched element. Actions remain host callbacks. CanopyX does not perform domain writes. Menus support action, checkbox, radio, separator, group and submenu entries, disabled states, badges, shortcuts, host-rendered icons and descriptions. A description (description on a generated item, CanopyMenuItem.Description in .NET) is a muted second line under the label and serves as the item's accessible description (aria-describedby). Separators and group labels cannot have descriptions.

A badge takes a tone: badgeTone on a generated item, CanopyMenuItem.BadgeTone in .NET (neutral, info, success, warning, danger, muted, or a host tone the page styles through data-tone). Built-in tones use the theme's status colours in light and dark, and a badge without a tone keeps the accent. On a menu bound with CanopyX.menu(root), setBadge(itemId, badge, tone) changes an item's badge as counts change, with the same arguments as a tab's setBadge. Use text or a number for the badge, or pass null or "" to remove it. Numbers use the page language when the browser supports it. Pass null or "none" to clear the tone, or omit the tone to keep it. The method finds the item in the menu or any of its submenus, whether open or closed, and returns false when the item is missing. The badge contributes to accessible names derived from the item's contents. Explicit names such as aria-label still take precedence.

const reports = CanopyX.menu('#reports');
reports.setBadge('failed', 4, 'danger');
reports.setBadge('failed', null);

Right-click, Shift+F10, the Context Menu key and a 500 ms touch press open the same menu. Touch uses a sheet. Links, editable controls, selected text and Shift+right-click retain the browser menu. A scrolling gesture cancels the pending touch press.

Keyboard, labels and print

Accordion headings are ordinary buttons in the Tab order: Enter and Space toggle a section, and Up, Down, Home and End move between headings, wrapping at the ends and skipping filtered sections. A disabled heading stays focusable and sets aria-disabled. Tabs use roving focus, arrow keys and Home/End; guarded or deferred tabs use manual activation unless explicitly overridden. Menu buttons open with Enter, Space or ArrowDown. Menus use arrow keys, Home/End, typeahead and logical submenu arrows. Disabled tabs and menu items remain focusable and announce their disabled state.

Pass translated labels in component options. The built-in locale packs include UI strings in Polish, German, Spanish, French and Italian. Content labels and action names remain host-owned.

Print shows tab and stepper panels with headings and omits overlays. Tabs print all panels by default; print: 'selected' includes only the selected panel and does not fetch inactive content.

For deferred content, await preparePrint() before opening the print dialog:

const sections = CanopyX.tabs('#workspace', {
  tabs: [{ id: 'activity', loader: async (item, signal) => {
    const response = await fetch('/workspace/activity', { signal });
    if (!response.ok) throw new Error('Activity could not be loaded');
    return await response.text(); // Trusted host HTML.
  } }]
});
await sections.ready;
await sections.preparePrint();
window.print();

Interactive steppers expose the same preparePrint(): Promise<void> method. ready covers component initialization and the initial panel; it does not load every deferred panel. preparePrint() waits for pending panel content and prepares the bodies required by the print mode. A loader failure rejects the promise, so the host can offer retry before calling window.print(). Destruction or an afterprint event cancels pending preparation with AbortError; late results are ignored. Concurrent preparation calls share the pending work.

The browser's synchronous beforeprint event materializes unvisited local templates and cached bodies. It cannot wait for asynchronous loaders: browser-menu printing without preparation may omit unloaded remote content. Preparation calls loaders only when required for printing, without changing selection, running navigation guards, marking steps visited, or replacing live form nodes. Loaders should return content and honor the supplied signal; they must not mutate the live panel themselves. A returned node is cloned for printing.

Deferred bodies cleared by keepAlive: false retain a detached snapshot for printing, including current form values. Print-only projections remain hidden on screen and are removed, together with their snapshots, after printing or destruction. Projection copies are inert; their IDs, control names and explicit form associations are removed to protect live forms. Style print content through classes. Normal navigation still reloads disposed bodies. Prepare again for each print attempt after content or selection changes; preparation does not wait for images, fonts, or host work outside the content loaders.

Reduced-motion preferences make navigation transitions and overlay motion instant. Forced-color styles retain borders, focus rings and state glyphs.

Slim entry point

A content page with no grid or tree can load canopyx-ui.js and canopyx-ui.css instead of a data view entry point. canopyx-ui.js holds the part loader, the theme helpers and the UI factories, about 5 KB gzipped against 57 KB for canopyx.js, and the components load the same canopyx-ui-* parts beside it. It offers mountUi, contextMenu, notify, tabs, stepper, accordion, toasts, lightbox, carousel, rating, mask, signature, select, dialog, drawer, popover, tooltip, menu, registerPart and setNonce.

<link rel="stylesheet" href="assets/canopyx-ui.css">
<script src="assets/canopyx-ui.js" defer></script>

In .NET, CanopyHtmlAssets.WriteTo("assets", CanopyAssetNaming.Plain, CanopyRuntime.Ui) writes the entry point and its parts, and GetParts(CanopyRuntime.Ui) lists the parts to embed in a self-contained page. In npm, @evotecit/canopyx/ui is its ES module, and /ui.js and /ui.css are the classic files.

Load one entry point per page. A page that also shows a grid or tree loads that view's entry point, and a page with flows loads the flow entry point (canopyx-flow-entry.js); both carry the same factories, so a page with menus, selects or toasts beside a form needs nothing else. A page that loads the UI entry point and later receives a grid, tree or matrix, in a refreshed region or a drawer, loads that view's entry point then: it takes the page over and keeps the components already created (see upgrading the entry point).