Core is the public entry point to the shared APIs of the Koobiq component library. It brings together configuration, types, base elements, interaction rules, and utilities. Components rely on these capabilities, which are also available for custom components and wrappers.

The public TypeScript API is imported from @koobiq/components/core:

import { KBQ_WINDOW, kbqThemeProvider } from '@koobiq/components/core';

SCSS has separate entry points, such as @koobiq/components/core/styles/visual.

Some areas are described in detail on dedicated pages:

ArticleTopic
Date formatterDateFormatter, date pipes, and time zone handling
Design tokensGlobal color and appearance variables
Filesize formatterKbqDataSizePipe and data-size units
FormsKbqForm and KbqFormElement classes, .kbq-form-vertical, .kbq-form-horizontal, and .kbq-form__row selectors, and the kbqForm and kbqFormElement aliases
HighlightkbqHighlightBackground and kbqHighlightBold pipes for highlighting text matches
Layout flexClasses and mixins for building flex layouts
LocalizationLocale registry, active locale, interface strings, and overrides
Number formatterPipes for precision, rounding, and displaying numbers in tables
Smart searchQuery normalization, search predicates, and match ranges for highlighting
ThemingKbqThemeService, appearance modes, named variants, and CSS variables
TypographyThe library's typographic styles and classes
ValidationErrorStateMatcher and the rules for transitioning a field to the error state

The rest of the public API is described below.

Koobiq reads global configuration from Angular providers. Provider functions merge the supplied configuration with defaults and return a provider of the expected type.

ProviderPurpose
kbqThemeProvider(config)Registers appearance variants; sets the initial mode, the initial variant by name through theme, and the storage key
kbqLocaleServiceProvider()Connects the localization service
kbqLocaleIDProvider(localeId)Sets the active locale
kbqLocaleConfigurationOverrideProvider(section, …)Overrides strings in one locale section
kbqA11yLocaleConfigurationProvider(config)Overrides screen-reader text
kbqSelectLocaleConfigurationProvider(config)Overrides strings for dropdown lists
kbqFormattersLocaleConfigurationProvider(…)Overrides the number formatting rules
kbqLocaleServiceLangAttrNameProvider(attrName)Sets the locale attribute name. Defaults to lang
kbqDateTimezoneProvider(timezone)Sets the time zone used to display dates
kbqSizeUnitsLocaleConfigurationProvider(config)Configures data-size units
kbqErrorStateMatcherProvider(matcher)Sets when form-field errors are shown
kbqShadowDomOverlayProvider(host?)Moves the overlay container into a Shadow DOM root

Component localization does not work without kbqLocaleServiceProvider().

ErrorStateMatcher is a class obtained through dependency injection. Configure its implementation and the timing of error display with kbqErrorStateMatcherProvider(matcher).

Tokens let you replace a setting or implementation through dependency injection.

TokenWhat it configures
KBQ_WINDOWA reference to window that is safe for server-side rendering
KBQ_THEME_CONFIGKbqThemeService settings: themes, mode, theme, and storageKey
KBQ_THEME_STOREAppearance mode (light, dark, auto) and pinned variant. Built-in implementations: KbqThemeLocalStorageStore, KbqThemeCookieStore
KBQ_STATE_STOREWhere components persist state across reloads. Built-in implementations: KbqLocalStorageStateStore, KbqSessionStorageStateStore
KBQ_STATE_SAVING_KEY_RESOLVERHow a component derives its storage key when it is given none. Defaults to kbqStructuralStateSavingKey
KBQ_STATE_SAVING_TTLHow long a web-storage entry survives without being written or read. Defaults to 90 days
KBQ_STATE_SAVING_ENABLEDWhat useStateSaving defaults to. Provide false to turn state saving off across an application
KBQ_LOCALE_SERVICEThe KbqLocaleService instance. No factory is provided, so provide it explicitly
KBQ_LOCALE_IDThe active locale. Defaults to ru-RU (KBQ_DEFAULT_LOCALE_ID)
KBQ_LOCALE_DATAAvailable locales, including custom locales
KBQ_LOCALE_CONFIGURATION_OVERRIDESPartial overrides of locale sections
KBQ_A11Y_LOCALE_CONFIGURATIONText read by screen readers
KBQ_SELECT_LOCALE_CONFIGURATIONStrings for dropdown lists
KBQ_FORMATTERS_LOCALE_CONFIGURATIONNumber formatting rules: decimal separators and rounding abbreviations
KBQ_LOCALE_SERVICE_LANG_ATTR_NAMEThe HTML attribute name for the locale. Defaults to lang
KBQ_DATE_LOCALEA date locale separate from the interface locale
KBQ_DATE_FORMATSDate parsing and display formats
KBQ_DATE_TIMEZONEThe time zone. Defaults to system
KBQ_NUMBER_FORMATTER_OPTIONSNumber precision and grouping
KBQ_SIZE_UNITS_LOCALE_CONFIGURATIONData-size units
KBQ_CHECKABLE_CLICK_ACTIONHow checkboxes and toggles react to clicks: noop, check, check-indeterminate
KBQ_SELECT_SCROLL_STRATEGYHow an open dropdown list behaves while the page scrolls
KBQ_SELECT_SEARCH_MIN_OPTIONS_THRESHOLDThe option count at which search appears. Defaults to 10

When a formatter token is not provided, the defaults apply: KBQ_NUMBER_FORMATTER_DEFAULT_OPTIONS for numbers and KBQ_SIZE_UNITS_DEFAULT_LOCALE_CONFIGURATION for data-size units.

KbqThemeService follows the operating system's color scheme through mode and lets you pin one registered variant by name.

A pinned variant takes priority over mode until it is reset. Use this mode when an application requires a specific appearance rather than a light, dark, or system mode.

The token first reads DOCUMENT.defaultView. If that value is unavailable, it falls back to the global window for backward compatibility. If neither source is available, the token throws an error.

Use the injected object to access innerWidth, getComputedStyle, matchMedia, and other window properties:

import { inject } from '@angular/core';
import { KBQ_WINDOW } from '@koobiq/components/core';

class Example {
    private readonly window = inject(KBQ_WINDOW);

    get isNarrow(): boolean {
        return this.window.innerWidth < 768;
    }
}

A component persists its state across reloads by applying the KbqStateSaving directive. The directive owns the parts that are easy to get wrong — which key to use, when writing is allowed, and turning an untrusted payload back into state — and writes through KBQ_STATE_STORE, a plain key–value bucket for JSON payloads.

Apply it with hostDirectives, forwarding both of its inputs so a consumer can configure persistence on the component itself, and inject it to drive it. Nothing else is declared: the directive needs no configuration.

@Component({
    selector: 'my-panel',
    hostDirectives: [{ directive: KbqStateSaving, inputs: ['useStateSaving', 'stateSavingKey'] }]
})
export class MyPanel {
    private readonly stateSaving = inject(KbqStateSaving);
}

Read once while initializing, write whenever the state changes, and remove it with clear(). Writes before that first read() are suppressed, so an input binding that changes the state during the parent's update pass cannot overwrite what is stored before the component has seen it.

ngAfterContentInit(): void {
    const savedState = this.stateSaving.read(normalizeMyState);

    this.stateSaving.applying(() => this.apply(savedState ?? this.defaultState()));
}

The directive does not decide what to persist or when to read it — that stays with the component, which is the only thing that knows its own state. read() takes the normalizer for the same reason.

The rules below come from the shapes real components hold; ignoring them produces state that restores into the wrong component, or not at all.

  • The key is derived from the document when none is given. KBQ_STATE_SAVING_KEY_RESOLVER builds it from the chain of tag names up to <body>, cut short by the first id on the way, which becomes the anchor — so restructuring the markup below that anchor moves the key and strands what was saved under the previous one. A host that is not in the document when it reads resolves to no key at all, and dev mode says so. Changing stateSavingKey at runtime moves the component to the entry under the new key: the directive reports the change, and the component restores from it.
  • Persist identifiers, not positions. An index survives a reload but not a reordering, and it silently restores the wrong thing rather than nothing.
  • Persist only JSON-serializable data. Never write component instances, TemplateRefs, functions, or date objects produced by a date adapter; persist a projection instead — an id rather than the object it identifies, an ISO string rather than a DateTime.
  • Normalize on read. getState() returns unknown on purpose: web storage is origin-wide and user-writable, so normalize has to reject anything that is not the expected shape, and it is also where a payload written by an earlier version is migrated.
  • Write a whole snapshot, not a change to one. A full snapshot drops values that no longer exist by itself; an incremental write leaves them behind to be restored forever.
  • Restore inside applying(). Restored state is applied through the component's own setters, which persist as they go — without the guard, restoring writes the state straight back.
  • Keep the precedence explicit. A controlled input wins over the persisted state, which wins over the default value.
  • Do not persist from an overlay. Components created imperatively into a CDK overlay have no stable key to persist under, so their state belongs to the component that owns them.
  • The store is read synchronously. A component reads once while it initializes and cannot wait, so a store whose getState returns a promise restores nothing and dev mode warns. To back the state with a server, load it before the application renders (provideAppInitializer) and serve it from memory.
  • Two components must not share a key. A key addresses a whole entry, not a namespace, so components sharing one overwrite each other; only an explicit stateSavingKey can collide, and dev mode warns when it does.
  • KBQ_STATE_SAVING_ENABLED decides before anything reads. KbqStateSavingService.setEnabled() is the runtime switch, but a component reads while it initializes, so provide the token to settle it up front — false turns state saving off application-wide, and individual components opt back in with [useStateSaving]="true".

The web-storage stores write under a kbq.state. prefix, so an entry cannot collide with one the application owns, and stamp every entry with the time it was written. An entry that goes KBQ_STATE_SAVING_TTL (90 days by default) without being written or read is collected the next time a store is constructed, which keeps keys stranded by a restructuring from accumulating; reading an entry refreshes it. To keep the state for the tab session only, provide KbqSessionStorageStateStore:

providers: [{ provide: KBQ_STATE_STORE, useExisting: KbqSessionStorageStateStore }];

A custom store — a backend, for instance — implements the KbqStateStore interface and is provided through the same token; in a component's own providers the replacement is scoped to that component instead of the whole application. When it is one of the browser storages, extend KbqWebStorageStateStore instead: it already guards against SSR, unavailable storage and unreadable payloads.

KbqStateSavingService is the application-wide view of it. It is provided in the root injector, so inject(KbqStateSavingService) anywhere reaches the same instance.

It reads from two sources, because neither covers the other. A registry of live components says who persists, under which key and what they currently hold — including a component given its own KBQ_STATE_STORE through its providers, which the root store cannot see. The store says what is actually stored, including the entries no live component claims: a component whose surrounding markup changed writes under a new key and strands the old entry, and only the store knows it is still there.

const stateSaving = inject(KbqStateSavingService);

stateSaving.components(); // who persists, under which key, holding what
stateSaving.keys(); // every key the store holds
stateSaving.orphans(); // the keys no live component claims

stateSaving.remove(key); // one entry, in the root store and in a component's own
stateSaving.clearOrphans(); // only what nothing claims any more
stateSaving.clear(); // everything

stateSaving.setEnabled(false); // stop persisting, application-wide

Everything is reported as a snapshot rather than a signal. Components register while their host is being created, which happens during change detection, and a signal written then is read back by a view that has already been checked (NG0100). Subscribe to changes — it emits when a component registers, persists, clears or is destroyed, when the service writes or removes, and when the store reports a write from another tab — and take a fresh snapshot in response.

keys() and orphans() need KbqStateStore.keys(), which is optional: a store that cannot enumerate leaves it out, and the service then reports the live components alone.

setEnabled(false) is the switch behind a "do not remember my interface" setting. It takes persistence away from every component at once — a component's own useStateSaving still has to be set for it to persist. It stops reading and writing, but neither removes what is already stored nor collapses what was already restored: call clear() for the first, reload for the second. It deliberately does not stop a component clearing its own state, since removing what was remembered carries the switch out rather than working against it.

write() is there for importing settings. A component restores once, while initializing, so a payload written under a live component's key reaches it only after a reload.

Angular CDK adds the overlay container to document.body by default. When an application runs inside Shadow DOM, modals, lists, tooltips, and toasts leave the shadow root. They also lose theme tokens declared on a .kbq-light or .kbq-dark ancestor.

kbqShadowDomOverlayProvider moves the overlay container into the shadow root:

import { bootstrapApplication } from '@angular/platform-browser';
import { kbqShadowDomOverlayProvider } from '@koobiq/components/core';

bootstrapApplication(AppComponent, {
    providers: [
        // The micro-frontend root element or any element inside its shadow tree.
        ...kbqShadowDomOverlayProvider(() => document.querySelector('my-mfe-root')!)
    ]
});

Limitations:

  • without an argument, the provider searches for the shadow root from the application root component;
  • the host element itself can resolve only an open shadow root;
  • when the supplied element is already inside a closed shadow root, the provider gets that root through getRootNode();
  • when no shadow root is found, the container stays in document.body;
  • the provider replaces the global OverlayContainer, so it cannot be combined with another implementation, such as FullscreenOverlayContainer;
  • CDK structural styles move with the container, while the application must add Koobiq styles and theme tokens to the shadow root itself.

The full description, including a scenario with one shared container for all micro-frontends, is on the Toast page.

Pop-up panels render into the application-wide overlay container (z-index: 1000), above kbq-top-bar and kbq-navbar (990). To have the panels opened from the page content slide under the bars while the content scrolls, mark the content area with kbqOverlayLayer:

<kbq-top-bar>…</kbq-top-bar>

<main kbqOverlayLayer>
    <router-outlet />
</main>
import { KbqOverlayLayer } from '@koobiq/components/core';

The panels of select, tree-select, timezone select, dropdown, popover, autocomplete, datepicker and inline edit whose trigger is inside the marked element move into a layer of their own with z-index: var(--kbq-overlay-layer-z-index, 980); the variable can be set on the element or any of its ancestors. Panels opened from those panels follow them. Modals, sidepanels, toasts, tooltips and the panels opened outside the element or from the bars stay above the bars.

Panels opened from kbq-top-bar, kbq-navbar and kbq-vertical-navbar stay above the bars even when a bar is inside the marked element. To keep the panels of other page chrome there too, mark it with kbqOverlayLayerExclude.

Conditions:

  • neither the element nor its ancestors create a containing block for fixed elements: transform, filter, perspective, contain, container-type;
  • neither the element nor its ancestors raise it above the bars with z-index.

Layered panels become descendants of the marked element: their events bubble through it, and inherited CSS properties come from it. The backdrop of such a panel also stays under the bars, so the bars remain clickable while the panel is open.

The Overflow Shadow directives show the edges of a scrollable area. A shadow appears at a header or footer when hidden content remains in the corresponding direction.

<div kbqOverflowShadowContainer #shadow="kbqOverflowShadowContainer" class="scrollable">
    <header [kbqOverflowShadowTop]="shadow">Header</header>

    <!-- content -->

    <footer [kbqOverflowShadowBottom]="shadow">Footer</footer>
</div>
APIPurpose
debounceScroll handling delay in milliseconds. Defaults to 0
shadowThe box-shadow value in the active state
KBQ_OVERFLOW_SHADOW_SOURCEEvent source and scrollable element for a custom wrapper
checkOverflow()Forces a state update

The default tokens are --kbq-shadow-overflow-normal-bottom and --kbq-shadow-overflow-normal-top.

The container tracks scrolling and element dimensions. If the content grows only through scrollHeight, the observer does not detect the change. Call checkOverflow() to update the state.

getSelectAllState and toggleSelectAll work through an adapter. The library does not prescribe how selected items are stored.

import { getSelectAllState, KbqSelectAllAdapter, toggleSelectAll } from '@koobiq/components/core';

const adapter: KbqSelectAllAdapter<Item> = {
    items: this.items,
    isSelectable: (item) => !item.disabled,
    isSelected: (item) => this.selection.isSelected(item),
    setSelected: (item, selected) => (selected ? this.selection.select(item) : this.selection.deselect(item))
};

const changed = toggleSelectAll(adapter, { allowDeselect: true });
const masterCheckboxState = getSelectAllState(adapter);

Details:

  • setSelected is called for every selectable item, including items whose state did not change; the implementation must be idempotent;
  • toggleSelectAll returns only the items that changed;
  • allowDeselect: true allows a repeated call to clear the selection;
  • unavailable items do not affect the master checkbox state;
  • an empty set has the unchecked state;
  • KbqSelectAllEvent describes the onSelectAll event;
  • shouldSelectSearchText determines whether the shortcut selects search text instead of toggling options.

Keyboard managers control the active item:

  • ListKeyManager — basic active-item management;
  • FocusKeyManager — additionally moves focus to the active item;
  • ActiveDescendantKeyManager — keeps focus on the container and marks the active item.
this.keyManager = new FocusKeyManager(this.items)
    .withVerticalOrientation()
    .withTypeAhead()
    .withHomeAndEnd()
    .withScrollSize(this.visibleRowsCount)
    .skipPredicate((item) => item.disabled);

The Koobiq classes are separate implementations of the CDK classes with the same names, with additions:

  • withScrollSize(), setNextPageItemActive(), and setPreviousPageItemActive() add page-wise movement;
  • previousActiveItemIndex stores the previous active index for range selection with Shift.

Validators are static methods that return a ValidatorFn.

MethodError keyError payload
minLength(min)minLength{ min, actual }
maxLength(max)maxLength{ max, actual }
minUppercase(min)minUppercase{ min, actual }
minLowercase(min)minLowercase{ min, actual }
minNumber(min)minNumber{ min, actual }
minSpecial(min)minSpecial{ min, actual }

PasswordValidators returns null for values that are not strings. Special characters are !, @, #, $, %, ^, &, *. A usage example is on the Form field page.

MethodError keyError payload
maxFileSize(maxSize)maxFileSize{ max, actual }
isCorrectExtension(accept)fileExtensionMismatch{ expected, actual }

accept takes extensions (.pdf) and MIME types (image/png) — the same values as the accept attribute of input[type=file]; the KbqFileTypeSpecifier type describes them. Examples are on the File upload page.

FileValidators expects a File object or an object with a file property. For an empty value it returns null, then accesses the file properties directly.

These types describe common input values across components. Use them in custom wrappers to keep them compatible with the Koobiq API.

TypeValues
KbqDefaultSizescompact, normal, big
KbqComponentColorstheme, theme-fade, contrast, contrast-fade, error, warning, success, empty
KbqOrientationhorizontal, vertical
KbqFlexDirection, KbqFlexWraprow / column, nowrap / wrap
PopUpPlacements, PopUpTriggers, PopUpSizesPosition, trigger, and size of pop-up elements
KbqMultipleInput, MultipleModeMultiple-selection mode for lists and trees

KbqColorDirective converts the color value into a kbq-<value> class. For example, color="error" adds kbq-error, while color="empty" adds kbq-empty. These classes are created at runtime, so they may not appear as complete strings in the sources.

resolveMultipleMode converts accepted multiple values into a selection mode. An unrecognized value enables single selection and reports a message in development mode.

The KbqPanelWidth, KbqPanelMinWidth, and KbqPanelMaxWidth types describe panel-width rules.

panelWidth valueBehavior
null, ''The width follows the content but is not less than the trigger width or panelMinWidth
'auto'The width equals the trigger width but is not less than panelMinWidth
NumberAn explicit width in pixels
CSS stringAn explicit width, such as fit-content or 20rem

panelMinWidth applies only to null, '', and 'auto'. The default is KBQ_PANEL_DEFAULT_MIN_WIDTH, which is 200 pixels.

KbqPanelMaxWidth limits content-based growth. For null, the --kbq-panel-size-width-max token is used. The limit does not make the panel narrower than the trigger or override an explicit width.

UtilityPurpose
kbqDeepMerge(base, patch), KbqDeepPartial<T>Recursively merges configurations
kbqInjectNativeElement<T>()Gets nativeElement from an injected ElementRef
isHtmlElement, isElement, isNull, isUndefinedChecks and narrows types
isBooleanChecks and narrows to boolean. Deprecated, removed in 22.0.0: use typeof value === 'boolean'
getNodesWithoutComments(nodes)Gets a list of nodes without comments
getContentNodes(element)Child nodes that carry content: comments and whitespace-only text ignored
supportsNativeDisabled(element)Whether the host tag accepts the native disabled attribute
escapeRegExp(value)Escapes a string for use in a regular expression
isMac()Detects the platform for keyboard shortcut labels
KbqMeasureScrollbarServiceMeasures the system scrollbar width. Deprecated, removed in 22.0.0
kbqInjectAutofilled()A signal that the browser autofilled a field
KbqNormalizeWhitespaceReplaces a thin space with a regular space when copying
kbqRevealSelection, kbqSetSelectionRangeSelects text and scrolls a field to the selected fragment

KbqMeasureScrollbarService returns 0 during server-side rendering.

KbqNormalizeWhitespace applies to fields with formatted numbers. When copying, the directive replaces the thin spaces between digit groups with regular spaces. It is not enabled by default. See the Input page for an example.

kbqInjectAutofilled() is called from a directive's injection context on an input or textarea.

Core exports utilities used to test Koobiq components. They are also suitable for testing application code built on the library.

UtilityPurpose
dispatchFakeEvent, dispatchKeyboardEvent, dispatchMouseEvent, dispatchTouchEventCreates and dispatches an event
createFakeEvent, createKeyboardEvent, createMouseEvent, createTouchEventCreates an event without dispatching it
typeInElement(value, element)Enters text with the full sequence of events
patchElementFocus(element)Controls focus and blur in the test environment
wrappedErrorMessage(error)Creates a regular expression for an error message

Prebuilt CSS files are described on the Installation and Theming pages.

For SCSS builds, use the following mixins:

@use '@koobiq/components' as components;
@use '@koobiq/components/core/styles/visual';

// Shared styles: overlay, visually hidden text, and the progress indicator.
@include components.kbq-core();

// Theme and global styles for directive-based components.
@include components.koobiq-theme();

// Typography classes.
@include components.koobiq-typography();

// Base page styles and breakpoint layouts.
@include visual.body-html();
@include visual.layouts-for-breakpoint();
Suggestions for improvement
If you found a mistake or want to improve the article, create an issue on GitHub.