Shared Utilities

This directory contains shared utilities and helper functions that are used across multiple components.

CSS Loading

The shared utilities include functionality to automatically load the base CSS file:

loadBaseCSS()

Ensures that the base CSS file is loaded. Will only add the CSS link if it hasn’t been added already. This function is safe to call multiple times and in testing environments.

import { loadBaseCSS } from '../shared/button-utils.js';

// Load the base CSS file
loadBaseCSS();

This function:

All components should call this function to ensure the base CSS is loaded.

Hosted and prefixed assets

Applications can import public component entries directly. The compiled utilities in this directory can share code through /assets/chunks/ dependencies. Native controls automatically load their base stylesheet from the component module’s asset root. This works for both component entries and shared chunks, including a prefix such as /dev/assets/.

<script type="module" src="/dev/assets/components/button/qds-button.js"></script>
<qds-button label="Prepare review"></qds-button>

Without an override, this example loads /dev/assets/css/q-base.css; icon styles and font URLs use the same asset root. It does not load the production CDN’s CSS for a self-hosted component. Explicit global, document, meta and runtime asset-base configuration still takes precedence; source-tree imports retain their content/assets/ behavior, and unrecognized module locations retain the production CDN fallback.

For a nonstandard bundle location, configure the asset base before importing components:

globalThis.QDS_ASSET_BASE_URL = 'https://example.com/preview/assets/';
await import('/application/qds-components.js');

See the isolated standalone demo. Its iframe has no preloaded stylesheet or documentation toolbar; the control loads its own base CSS and follows the parent documentation theme.

Button Utilities

The button-utils.js module provides functions and helpers for creating consistent button-like components:

Functions

getBaseButtonStyles()

Returns a string of CSS that provides consistent styling for button-like components.

import { getBaseButtonStyles } from '../shared/button-utils.js';

// Use in a component
render() {
  this.shadowRoot.innerHTML = `
    <style>
      ${getBaseButtonStyles()}
      /* Additional styles */
    </style>
    <!-- Component HTML -->
  `;
}

createButtonTemplate(iconClass, styles = '')

Creates a standard button template with an icon.

import { createButtonTemplate } from '../shared/button-utils.js';

// Use in a component
render() {
  this.shadowRoot.innerHTML = createButtonTemplate('pi-bell', `
    /* Additional styles */
  `);
}

setupButtonEvents(component, eventName = 'click', eventDetail = {})

Sets up standard event handling for button components.

import { setupButtonEvents } from '../shared/button-utils.js';

// Use in a component
connectedCallback() {
  if (!this.isConnected) return;
  this._cleanup = setupButtonEvents(this, 'custom-event', { foo: 'bar' });
}

disconnectedCallback() {
  if (this._cleanup) {
    this._cleanup();
    this._cleanup = null;
  }
}

createBaseButtonComponent(iconClass, additionalStyles = '')

Creates a complete component class with standard button behavior. This function automatically calls loadBaseCSS() to ensure the base CSS is loaded.

import { createBaseButtonComponent } from '../shared/button-utils.js';

// Create a simple button component with a cog icon
const MyButtonComponent = createBaseButtonComponent('pi-cog');

// Register the component
customElements.define('my-button', MyButtonComponent);

Usage Examples

Simple Button Component

import { createBaseButtonComponent } from '../shared/button-utils.js';

// Create a settings button component with the cog icon
const QdsSettingsButton = createBaseButtonComponent('pi-cog');

// Register the component
customElements.define('qds-settings-button', QdsSettingsButton);

Component with Custom Behavior

import { getBaseButtonStyles, setupButtonEvents } from '../shared/button-utils.js';

class QdsCustomButton extends HTMLElement {
  constructor() {
    super();
    this.attachShadow({ mode: 'open' });
    this.render();
  }

  connectedCallback() {
    if (!this.isConnected) return;
    this._cleanup = setupButtonEvents(this, 'custom-click', { data: 'value' });
  }

  disconnectedCallback() {
    if (this._cleanup) {
      this._cleanup();
      this._cleanup = null;
    }
  }

  render() {
    this.shadowRoot.innerHTML = `
      <style>
        ${getBaseButtonStyles()}
        /* Additional styles */
      </style>
      <button part="button">
        <i class="pi pi-custom icon" part="icon"></i>
      </button>
    `;
  }
}

customElements.define('qds-custom-button', QdsCustomButton);

Benefits

Form Control Utilities

The form-control.js module provides shared infrastructure for form-associated custom elements (text-input, numeric-input, select, checkbox, radio-group, date-picker).

attachInternalsSafe(host)

Calls attachInternals() behind a try/catch so jsdom (which does not implement ElementInternals) does not throw.

ValidityTracker

Tracks validity flags with a QdsValidity fallback when ElementInternals is unavailable. Delegates to setValidity() / checkValidity() / reportValidity() when internals are present.

dispatchValidityChange(host, tracker)

Dispatches a qds-validity-change custom event (bubbles, composed) with valid, validity, and message in the detail.

getFormControlStyles()

Returns shared CSS for form control surfaces — height, border, focus ring, states (resting, hover, focus, readonly, disabled, invalid). Ensures a text-input and a select side by side are indistinguishable in their resting frame.

Helpers

Popover Utilities

The popover-utils.js module provides shared popover positioning and dismissal for overlay-style controls (select, date-picker).

PopoverController

Manages a popover’s open/close lifecycle, positioning, dismissal, and single-open-at-a-time coordination.

Renders inside the component’s shadow root (not portalled to <body>). Flips to top when below-space is insufficient. One open at a time via qds-popover-open document event.

Semantic List Recipes

Use native HTML for plain lists and labelled details. These supported recipes add no JavaScript or custom-element registration. Use the Listbox primitive for selectable options when that behavior is required; a list of content or links is not a listbox.

<section aria-labelledby="review-contacts">
  <h2 id="review-contacts">Review contacts</h2>
  <ul aria-label="Portfolio review contacts">
    <li>Maya Patel — Investment committee</li>
    <li>Jordan Lee — Portfolio operations</li>
  </ul>
</section>
<ol aria-label="Quarter-end preparation">
  <li>Review operating results</li><li>Validate assumptions</li><li>Prepare committee materials</li>
</ol>
<dl>
  <dt>Invested capital</dt><dd>$75 million</dd>
  <dt>Reporting period</dt><dd>Quarter 3, 2026</dd>
</dl>

Keep li as direct children of ul/ol; dt supplies the term and dd the value. Group each term with its corresponding value(s). Use a heading/accessible label when several lists need distinguishing. If removing list markers for a card layout, retain role="list" on the native list to preserve list exposure in Safari. Use responsive layout, meaningful text and existing QDS tokens; avoid color-only meaning or forcing selection roles onto ordinary content. Actionable children retain their own accessible names, focus outlines and 44px touch targets.

Northwind uses a description list in the company investment snapshot and a labelled contact list with role/identity graphics and nested responsibility details at /#/admin/team. Filtering by role changes both the contact list and the existing table. These are fictional local QAPI fixtures. See the shared demo for unordered, ordered and description-list examples in both themes.

Inline choice lifecycle

The internal QdsChoiceBase in choice-base.ts supplies cloned typed options, scalar/multiple current values and reset defaults, pending value identity, native FormData/state restoration, disabled-fieldset handling, validation feedback and listener cleanup. It renders labels as text and keeps hint/error layout stable. Derived controls own their keyboard and selection semantics.

See Segmented Control and its native demo for single/multiple choices and form validation. The generated Quangular integration is exercised by stage and sector filtering at /#/investments/pipeline. This utility imports no popup selector or framework runtime.

Native fieldset recipe and disabled state

Group related fields with a native fieldset and descriptive legend. Keep it in the light-DOM form tree so native form ownership, submission and the first-legend exemption remain platform behavior.

<fieldset id="reporting-fields">
  <legend>Operating metrics</legend>
  <qds-numeric-input label="Uptime (%)" name="uptime" step="0.1" min="0" max="100"></qds-numeric-input>
  <qds-checkbox-group label="Notify reviewers" name="reviewers"></qds-checkbox-group>
</fieldset>

Native form-associated controls retain the platform disabled state separately from their own disabled attribute. Setting a child’s disabled property to false cannot bypass a disabled parent; re-enabling the parent preserves an explicitly disabled child. Shared form styles include native :disabled state as well as the own attribute. No token values change. See the checkbox-group demo, the existing field demos’ reporting-fieldset examples and error summary for field correction.

Composed focus utilities

focus-utils.js contains deepActiveElement(root?) and overlayContains(owner, node) for open-shadow-root and slotted-content focus handling. Inline components can import this small module without loading overlay positioning or controllers. Existing exports from overlay-utils.js, including overlayActiveElement, remain compatible and refer to the same functions. Keep overlay lifecycle, dismissal, positioning and scroll locking in the overlay module.

redirectValidationFocus is an internal listener shared by inline choices and file upload. Bind it to the owning component, register it on a native input excluded from Tab order and the accessibility tree, and remove the same listener on disconnect. The browser may attach native validation UI to the input without replacing the visible control’s content. A guarded microtask then calls the owner’s public focus() only if that input still owns shadow focus and the owner is connected. This preserves native reporting/cancellation, avoids taking focus back after user navigation and supports repeated reporting in Firefox and WebKit. No timers, overlay controller or framework dependency are required. When an application’s error summary owns focus, check fields with checkValidity() and then focus the populated summary after rendering; field-level reportValidity() owns its own native focus sequence.

Option data and list rendering

option-model.js exposes normalizeChoiceOptions(options), preserving the existing cloned string-identity, label fallback, duplicate, disabled, group and description rules. It has no DOM or field runtime dependency. option-list.js exposes createListboxOption(option) and renderGroupedOptions(container, options, createOption) for plain-text grouped listbox content. Consumers own same-root option IDs, active/selected state and keyboard policy. Keeping model and view modules separate lets small segmented/checkbox controls share identity rules without loading popup or listbox rendering.

The optional FieldValidity.badInput flag supports future typed-input constraints without adding a key to existing textarea/switch validity objects. Overlay Escape listeners ignore IME composition key events; normal dismissal policy and listener cleanup remain unchanged.