Skip to main content

Widgets

Component

An sn_aiux widget's component field holds a Lit web-component class that extends AIUXWidgetElement. This page covers the AIUX-specific authoring surface: the base classes, the framework-injected instance members, the lifecycle hooks, the static declarations, the services available via import, and the framework's Lit contexts and directives.

For raw Lit (htmlcssrepeat, etc.) see the Lit page. For the pre-built <aiux-*> web components see Daisy. For the server side see Server Script.


Base classes

Imports from @servicenow/aiux-components-core.

SymbolKindPurpose
AIUXWidgetElementclassBase for widget components — adds this.server.*, this.aiContext, this.deps, this.trackEvent, this.logger on top of LitElement.
AIUXElementclassBase for design-system components (no server data binding).
WithDatamixin functionWithData(BaseClass) — opt-in server-data binding for custom base classes.
UxKitElementclassLow-level base from ux_kit/core.

Minimal widget skeleton:

import { html } from 'lit';
import { AIUXWidgetElement } from '@servicenow/aiux-components-core';

class MyWidget extends AIUXWidgetElement {
  static properties = {
    title: { type: String },
  };
  createRenderRoot() { return this; }
  render() {
    return html`<h2>${this.title}</h2>`;
  }
}

Instance members (this.*)

Available on any AIUXWidgetElement.

MemberKindDescription
this.datapropertyServer script output payload.
this.server.get(request)methodCall server script with {action, data}. Returns Promise.
this.server.update()methodUpdate server data.
this.server.refresh()methodRe-run server script and refresh this.data.
this.aiContextpropertyCurrent AI context object.
this.setAiContext(ctx)methodUpdate AI context.
this.loggerpropertyFramework logger.
this.trackEvent(name, data?)methodTrack analytics event.
this.deps.servicespropertyDependency-injected services.
this.deps.directivespropertyDependency-injected directives.
this.renderRootpropertyRender root (light or shadow DOM).
this.shadowRootpropertyShadow root.
this.updateCompletepropertyPromise resolved after the next update.
this.isConnectedpropertyIn-DOM flag.
this.requestUpdate(name?, oldValue?)methodForce a re-render.
this.dispatchEvent(event)methodDispatch a custom event.
this.querySelector(selector)methodQuery a light-DOM child.

Lifecycle hooks

HookWhen
connectedCallback()Element added to the DOM.
disconnectedCallback()Element removed.
render()Return a TemplateResult (required).
firstUpdated(changedProperties)After the first render.
updated(changedProperties)After every render.
willUpdate(changedProperties)Before update / render.
shouldUpdate(changedProperties)Return false to skip the next render.
performUpdate()Override to batch / defer updates.
getUpdateComplete()Override to await child updates.
createRenderRoot()Override to change render target. return this opts out of Shadow DOM and into light DOM.
attributeChangedCallback(name, old, value)Raw attribute change.
adoptedCallback()Element moved to a new document.
onDataChange(newData, oldData)AIUX-specific — fires when server data updates.

Static class members

class MyWidget extends AIUXWidgetElement {
  // Reactive properties — same as Lit
  static properties = {
    sysId: { type: String },
    count: { type: Number },
  };

  // Component-scoped CSS (alternative to the widget record's `style` field)
  static styles = css`
    :host { display: block; }
  `;

  // Inject framework services / directives
  static dependencies = { services: ['i18n', 'notifications'], directives: [] };
  // Shorthand for services-only:
  static dependencies = ['i18n', 'notifications'];

  // AI client tools — see the AI Integration section
  static client_tools = {
    refresh: {
      definition: function() { this.server.refresh(); },
      description: '[UI CONTROL] Reload the widget data.',
      arguments: [],
    },
  };
}

Services

Top-level singletons exported from @servicenow/aiux-services@servicenow/aiux-utils, and @servicenow/aiux-context. Import the service name to use any of its methods.

i18n — translations

import { i18n } from '@servicenow/aiux-services'

MethodReturnsDescription
i18n.getMessage(key, args?)stringGet a translated string. key is a message key or {message, code, comment} object.
i18n.loadMessages()PromiseBulk-load translations.
i18n.loadMessage(key)PromiseLoad a single message by key.

notifications — toast notifications

import { notifications } from '@servicenow/aiux-services'

MethodReturnsDescription
notifications.add(notification)string (id)Add a custom notification {type, message, duration?, actions?}.
notifications.addInfoNotification(msg)string (id)Info toast.
notifications.addSuccessNotification(msg)string (id)Success toast.
notifications.addWarningNotification(msg)string (id)Warning toast.
notifications.addErrorNotification(msg)string (id)Error toast.
notifications.remove(id)voidRemove by id.
notifications.clear()voidClear all active notifications.
notifications.getNotifications()ArrayGet all active.
notifications.subscribe(callback)UnsubscribeWatch notification state changes.

locationService — routing

import { locationService } from '@servicenow/aiux-services'

MethodReturnsDescription
locationService.navigate(path, opts?)voidNavigate to a path. opts: {replace?, state?}
locationService.path()stringCurrent path.
locationService.fullPath()stringFull path including experience prefix.
locationService.url()stringCurrent URL.
locationService.absUrl()stringAbsolute URL.
locationService.experience()stringCurrent experience name.
locationService.page()stringCurrent page name.
locationService.param(key)string|nullSingle URL parameter.
locationService.params()ObjectAll route parameters as an object.
locationService.search()stringSearch string.
locationService.searchParam(key)string|nullGet a search param.
locationService.hasSearchParam(key)booleanCheck for a search param.
locationService.updateSearchParams(params)voidMerge search params.
locationService.setSearchParams(params)voidReplace all search params.
locationService.removeSearchParam(key)voidRemove one.
locationService.hash()stringURL hash.
locationService.setHash(hash)voidSet hash.
locationService.clearHash()voidClear hash.
locationService.replace(path)voidReplace URL without adding history.
locationService.back()voidGo back.
locationService.subscribe(callback)UnsubscribeWatch for route changes.
locationService.onBeforeNavigate(callback)UnsubscribeHook before navigation; return false to cancel.

recordWatcherService — reactive GlideRecord

import { recordWatcherService } from '@servicenow/aiux-services'

MethodReturnsDescription
recordWatcherService.createReactiveWatcher(host, table, filter, cb)WatcherLive-watch a table/filter; callback fires on insert/update/delete.

themeService — dark/light mode

import { themeService } from '@servicenow/aiux-services'

MethodReturnsDescription
themeService.getThemeMode()stringCurrent mode.
themeService.setThemeMode(mode)void"dark" or "light".

mobileAppBridgeService — native mobile bridge

import { mobileAppBridgeService } from '@servicenow/aiux-services'

MethodReturnsDescription
mobileAppBridgeService.isMobileApp()booleanRunning inside the native ServiceNow mobile app?
mobileAppBridgeService.isInitialized()booleanBridge ready?
mobileAppBridgeService.getBridge()ObjectBridge instance.
mobileAppBridgeService.init()voidInitialize.
mobileAppBridgeService.destroy()voidDestroy.

userPreferencesService — user preferences

import { userPreferencesService } from '@servicenow/aiux-services'

MethodReturnsDescription
userPreferencesService.isReduceMotionEnabled()booleanReduced-motion preference.
userPreferencesService.getUserPreference(name, default?)anyRead a preference value.
userPreferencesService.setUserPreference(name, value)voidSet in memory.
userPreferencesService.saveUserPreference(name, value)PromisePersist to server.
userPreferencesService.getBooleanPreferenceValue(name, default?)booleanRead as boolean.
userPreferencesService.subscribe(name, callback)UnsubscribeWatch a preference.
userPreferencesService.getUserPreferences()MapAll preferences.
userPreferencesService.fetchLanguages()PromiseAvailable languages.

ariaLive — screen-reader announcements

import { ariaLive } from '@servicenow/aiux-services'

MethodReturnsDescription
ariaLive.announce(message, politeness?, options?)voidAnnounce. politeness: "polite" | "assertive" | "off".
ariaLive.announcePolite(message, options?)voidPolite announcement.
ariaLive.announceAssertive(message, options?)voidUrgent announcement.
ariaLive.clear()voidClear pending.
ariaLive.isInitialized()booleanReady?
ariaLive.initialize()voidInitialize.
ariaLive.destroy()voidDestroy.

snHttp — HTTP client

import { snHttp } from '@servicenow/aiux-utils'

MethodReturnsDescription
snHttp.get(url, config?)PromiseGET. config: {headers?, signal?, responseType?, batch?}.
snHttp.post(url, body?, config?)PromisePOST.
snHttp.put(url, body?, config?)PromisePUT.
snHttp.delete(url, config?)PromiseDELETE.
snHttp.patch(url, body?, config?)PromisePATCH.

Standalone utilities

import { ... } from '@servicenow/aiux-utils'

SymbolReturnsDescription
getUser(){roles, userId, firstName, lastName, name, departmentID} | nullCurrent user info (client-side).
getSessionLanguage()stringSession language code (e.g. "en").
setAiuxGlobal(key, value)voidWrite to window.NOW.aiux.
getAiuxGlobal(key, default?)anyRead from window.NOW.aiux.
CHAT_CHANNELconstantChat channel name.

Lit contexts

For use with ContextConsumer (see Lit) to read framework state.

import { ... } from '@servicenow/aiux-context'

ContextHolds
routeContextCurrent route info.
experienceContextCurrent experience config.
userPreferencesContextUser preferences.
widgetRenderingContextWidget origin tracking.
mobileAppBridgeContextMobile bridge state.

Example:

import { ContextConsumer } from 'lit';
import { experienceContext } from '@servicenow/aiux-context';

class MyWidget extends AIUXWidgetElement {
  experienceCtx = new ContextConsumer(this, {
    context: experienceContext,
    subscribe: true,
    callback: (value) => { this.experience = value; this.requestUpdate(); },
  });
}

AIUX-specific directives

Lit directives specific to sn_aiux.

import { ... } from '@servicenow/aiux-directives'

SymbolKindSignatureDescription
spreadPropsdirective${spreadProps(obj)}Spread an object of properties/attributes onto an element.
timeAgodirective${timeAgo(timestamp, options?)}Auto-updating relative time. options: {live?, formatter?}.
liveRegionPolitedirective${liveRegionPolite(options?)}ARIA polite live region.
liveRegionAssertivedirective${liveRegionAssertive(options?)}ARIA assertive live region.
getTimeAgofunctiongetTimeAgo(timestamp)Returns {value, unit, isFuture, isJustNow}.
formatTimeAgofunctionformatTimeAgo(timeData)Format a getTimeAgo result as a string.