Examples
Context and change feedback
Use authorized context, projection notifications and shared feedback.
Example type Recipe
Overview
Context, changes and feedback
Use host-provided context and UI behavior inside an App surface. This example debounces an App-owned search, listens for the exact authorized Resource projection, formats a timestamp in the host locale, and refreshes with shared feedback. The parent owns the authorized API request, Resource identity, and stable callbacks. A projection signal is not data or authorization: refetch through the server and recheck permissions. Visibility controls whether this example listens; choose freshness behavior for the actual task.
Frontend host contracts · Resource projections
Attachments.tsx lists the first page of a saved Resource’s attachments and demonstrates upload and confirmed deletion. Render it only after the parent has established access; the server must authorize every request. Implement pagination for complete lists and localize the sample labels for your App.
More host contracts
OrganizationLookups.tsxcompares membership, affiliation, assignment and applicability; use each only for its stated purpose. The administration surface requires an authorized route. Adapt pagination to your workflow.ResourceInteractions.tsxdemonstrates the route frame, Inspector, create continuation, local draft actions and reauthentication. Supply server-authorized identities and actions. Local draft actions do not save a record; the server must authorize the eventual write.DashboardMetric.tsxanddashboard-registration.tsshow a tool-backed widget and eager or lazy registration. Replace the tool with one declared by your App and include tenant and organization scope in the query key.InsightsFilter.tsxpasses inclusive dates to the report owner.FileOperations.tsxuses a host-supported upload purpose, waits for validation, opens an authorized file and observes an existing background-operation ticket. It does not start or replay a migration.SignaturePreparation.tsxshows host components. Supply state from authorized revision-bound endpoints. Choose the editor appropriate to the step; show the exact preview only for the current saved revision and connect the request dialog to App-owned handlers.
bindNexiaAppRequestServices belongs to the SDK build facade and configureNexiaAppFrontendHost is called by Core; ordinary App code must not call either. The examples assume host router, query, permissions and request context. Translate labels and implement pagination, retry and authorization for your workflow.
ReferencePicker.tsx demonstrates the authorized selector and distinguishes an absent dependency from blocked states. MigrationHelpers.ts observes a submitted operation without replaying it; the server-owned run remains the evidence. ContractHelpers.ts shows strict organization scope, permission presentation, status handling and parsing.
ApprovalSubmission.ts preserves the idempotency key across ambiguous responses. An accepted submission is not an approved case; observe its result through the authorized workflow. TestHost.ts configures the App suite’s own test fixtures.
PresentationHelpers.ts groups already-authorized catalog entries, represents an empty form value and invalidates the owner-scoped reference cache after a confirmed write. SDK status lists (RESOURCE_REFERENCE_STATUSES, APP_AVAILABILITY_STATES, HANDOFF_RESULT_STATES, APPROVAL_STATES, APPROVAL_STEP_KINDS) and signature document data lists describe their respective wire contracts; do not substitute labels or infer permission from them. DMN_EDITOR_HIT_POLICIES describes editor choices. NEXIA_READ_ONLY_HEADER is a transport contract for declared read-only calls, not an authorization bypass. Deprecated allowsManualAppFallback and isRetryableHandoffFailure remain aliases; new code uses permitsManualFallback and isRetryableFailure.
Signature schema lists SIGNATURE_DOCUMENT_DATA_CLASSIFICATIONS, SIGNATURE_DOCUMENT_DATA_FIELD_TYPES, SIGNATURE_DOCUMENT_DATA_FORMATTERS, SIGNATURE_DOCUMENT_DATA_LOOKUP_MODES and SIGNATURE_DOCUMENT_DATA_STATUSES expose wire vocabulary, not live capability grants. queryKeys includes host query-key helpers; use the matching authorized scope. parseRefreshHint and resolveTokens support dashboard configuration; isAuthorityRevocationError distinguishes lost access. withOperatingUnit builds a legacy single-unit URL; new page-owned lists use organization list scope. NX_LINE_CHART_MAX_SERIES, NX_DONUT_MAX_SEGMENTS and chartCategoricalColor help keep charts readable.
Included files
Context and events
docs/developers/examples/frontend-host-hooks/ContextAndEvents.tsximport { useEffect, useState } from "react";
import type { ResourceProjectionChangeSubscription } from "@nexia/sdk/host";
import {
NxButton,
NxSearchField,
useActiveWorkTabId,
useContextQuery,
useDateTimeFormatter,
useDebouncedValue,
useFeedbackAction,
useIsActiveWorkTabVisible,
useResourceProjectionChange,
} from "@nexia/sdk/host";
/** The caller supplies an authorized Resource identity and refetches its own API. */
export function ContextAndEvents({ resource, updatedAt, onSearch, onRefresh }: {
resource: ResourceProjectionChangeSubscription["resource"];
updatedAt: string | null;
onSearch: (value: string) => void;
onRefresh: () => Promise<void>;
}) {
const [search, setSearch] = useState("");
const debouncedSearch = useDebouncedValue(search, 300);
const { data: context } = useContextQuery();
const tabId = useActiveWorkTabId();
const visible = useIsActiveWorkTabVisible();
const { formatDateTime } = useDateTimeFormatter();
const refresh = useFeedbackAction(onRefresh, {
success: "Refreshed",
error: "Could not refresh",
});
useEffect(() => { onSearch(debouncedSearch); }, [debouncedSearch, onSearch]);
useResourceProjectionChange({ tenantId: context?.tenant?.id, resource,
enabled: Boolean(context?.tenant?.id && tabId && visible),
onChanged: () => { void refresh.run(); } });
return <div className="space-y-stack">
<NxSearchField value={search} onChange={setSearch} aria-label="Search" />
<p>Updated: {formatDateTime(updatedAt)}</p>
<NxButton type="button" disabled={refresh.pending} onClick={() => void refresh.run()}>
Refresh
</NxButton>
</div>;
}Resource attachments
docs/developers/examples/frontend-host-hooks/Attachments.tsximport { useState } from "react";
import { NxButton, useAttachments, useDeleteAttachment, useMessage, useUploadAttachment } from "@nexia/sdk/host";
/** Render only after the parent has authorized access to the saved Resource. */
export function Attachments({ tenantId, resourceType, resourceId, canUpdate }: {
tenantId: string;
resourceType: string;
resourceId: string;
canUpdate: boolean;
}) {
const attachments = useAttachments(tenantId, resourceType, resourceId);
const upload = useUploadAttachment(tenantId, resourceType, resourceId);
const remove = useDeleteAttachment(tenantId, resourceType, resourceId);
const { confirm } = useMessage();
const [error, setError] = useState<string | null>(null);
return <section aria-label="Attachments">
{attachments.isLoading ? <p>Loading attachments…</p> : null}
{attachments.isError ? <p role="alert">Could not load attachments. <NxButton onClick={() => void attachments.refetch()}>Retry</NxButton></p> : null}
{attachments.isSuccess && attachments.data.data.length === 0 ? <p>No attachments.</p> : null}
<ul>{attachments.data?.data.map((item) => <li key={item.public_id}>
{item.download_url ? <a href={item.download_url}>{item.original_name}</a> : item.original_name}
{canUpdate ? <NxButton disabled={remove.isPending} onClick={() => void (async () => {
if (!await confirm(`Delete ${item.original_name}?`, { variant: "destructive" })) return;
setError(null);
remove.mutate(item.public_id, { onError: () => setError("Could not delete attachment.") });
})()}>Delete</NxButton> : null}
</li>)}</ul>
{attachments.data && attachments.data.meta.last_page > 1 ? <p>Only the first page is shown.</p> : null}
{canUpdate ? <label>Upload attachment <input type="file" disabled={upload.isPending} onChange={(event) => {
const file = event.target.files?.[0];
event.target.value = "";
if (!file) return;
setError(null);
upload.mutate(file, { onError: () => setError("Could not upload attachment.") });
}} /></label> : null}
{error ? <p role="alert">{error}</p> : null}
</section>;
}Organization and reference lookups
docs/developers/examples/frontend-host-hooks/OrganizationLookups.tsximport { useState } from "react";
import {
NxButton, NxCombobox, OperatingUnitScopeField,
useAffiliatedOperatingUnits, useApprovalRoutePoliciesQuery, useApprovalSharedLinesQuery,
useAssignableOperatingUnits, useLegalEntitiesQuery, useLegalEntityApplicabilityQuery,
useLegalEntityMembersQuery, useOperatingUnitScope, useOperatingUnitSelection,
useOperatingUnitsQuery, useParties, useTrustedAssetsQuery,
} from "@nexia/sdk/host";
/** Use the persisted owner on edit; never replace it with a default from these lists. */
export function OrganizationLookups({ tenantId, ownerId, permission }: {
tenantId: string; ownerId: string | null; permission: string;
}) {
const entities = useLegalEntitiesQuery(tenantId);
const applicable = useLegalEntityApplicabilityQuery(tenantId, permission);
const members = useLegalEntityMembersQuery(tenantId, ownerId, { perPage: 20 }, !!ownerId);
const affiliated = useAffiliatedOperatingUnits(tenantId, ownerId, permission, !!ownerId);
const assignable = useAssignableOperatingUnits(tenantId, ownerId, permission, !!ownerId);
const memberships = useOperatingUnitsQuery(tenantId, ownerId, "memberships", permission, !!ownerId);
if (!ownerId) return <p>Select an authorized owner first.</p>;
const failed = [entities, applicable, members, affiliated, assignable, memberships].some((q) => q.isError);
if (failed) return <p role="alert">A lookup failed. Refresh the page to retry.</p>;
if ([entities, applicable, members, affiliated, assignable, memberships].some((q) => q.isLoading)) return <p>Loading choices…</p>;
return <section aria-label="Organization references">
<p>Visible entities: {(entities.data?.legal_entities ?? []).map((x) => x.name).join(", ") || "None"}</p>
<p>Applicable entities: {(applicable.data?.data ?? []).map((x) => x.name).join(", ") || "None"}</p>
<p>Members: {(members.data?.data ?? []).map((x) => x.name).join(", ") || "None"}</p>
<p>Affiliated: {(affiliated.data?.operating_units ?? []).map((x) => x.name).join(", ") || "None"}</p>
<p>Assignable: {(assignable.data?.operating_units ?? []).map((x) => x.name).join(", ") || "None"}</p>
<p>Memberships: {(memberships.data?.operating_units ?? []).map((x) => x.name).join(", ") || "None"}</p>
</section>;
}
export function ApprovalReferences({ tenantId, ownerId }: { tenantId: string; ownerId: string | null }) {
const routes = useApprovalRoutePoliciesQuery(tenantId, ownerId, !!ownerId);
const lines = useApprovalSharedLinesQuery(tenantId, ownerId, !!ownerId);
const [route, setRoute] = useState<string | null>(null);
if (!ownerId) return <p>Select an owner first.</p>;
if (routes.isError || lines.isError) return <p role="alert">Could not load approval choices. <NxButton onClick={() => { void routes.refetch(); void lines.refetch(); }}>Retry</NxButton></p>;
return <section aria-label="Approval references">
<NxCombobox placeholder="Select approval route" ariaLabel="Approval route" value={route} loading={routes.isLoading} options={(routes.data?.data ?? []).filter((x) => x.status === "active").map((x) => ({ value: x.key, label: x.name }))} onChange={setRoute} />
<p>Available shared lines: {(lines.data?.data ?? []).filter((x) => x.resolved && !x.unavailable).map((x) => x.name).join(", ") || "None"}</p>
</section>;
}
export function ReferenceSearch({ tenantId, ownerId, bindingKey, bindingVersion, kind }: {
tenantId: string; ownerId: string | null; bindingKey: string; bindingVersion: string; kind: string;
}) {
const [search, setSearch] = useState("");
const parties = useParties(tenantId, { search, perPage: 20 });
const assets = useTrustedAssetsQuery(tenantId, ownerId, { bindingKey, bindingVersion, kind }, !!ownerId);
return <section aria-label="Reference search">
<label>Search parties <input value={search} onChange={(event) => setSearch(event.target.value)} /></label>
{parties.isError ? <p role="alert">Could not load parties.</p> : <ul>{(parties.data?.parties ?? []).map((party) => <li key={party.public_id}>{party.display_label}</li>)}</ul>}
{assets.isError ? <p role="alert">Could not load trusted assets.</p> : <ul>{(assets.data?.data ?? []).map((asset) => <li key={asset.public_id}>{asset.label}</li>)}</ul>}
</section>;
}
/** Use only from a route that authorizes organization administration. */
export { OperatingUnitManagementSurface as OrganizationAdministration } from "@nexia/sdk/host";
/** These are alternative URL-backed scope models; mount only the one your route needs. */
export function GrantScopedUnit({ tenantId, ownerId, permission }: { tenantId: string; ownerId: string | null; permission: string }) {
const scope = useOperatingUnitScope(tenantId, ownerId, permission, !!ownerId);
if (!ownerId) return <p>Select an owner first.</p>;
if (scope.isError) return <p role="alert">Could not load the operating scope.</p>;
if (scope.isLoading) return <p>Loading scope…</p>;
return <OperatingUnitScopeField scope={scope} />;
}
export function AssignableUnitSelection({ tenantId, ownerId, permission }: { tenantId: string; ownerId: string | null; permission: string }) {
const selection = useOperatingUnitSelection(tenantId, ownerId, permission, !!ownerId);
if (!ownerId) return <p>Select an owner first.</p>;
if (selection.isError) return <p role="alert">Could not load operating units.</p>;
return <NxCombobox placeholder="Select operating unit" ariaLabel="Operating unit" value={selection.selectedPublicId}
loading={selection.isLoading} options={selection.operatingUnits.map((unit) => ({ value: unit.public_id, label: unit.name }))} onChange={selection.select} />;
}Resource interactions
docs/developers/examples/frontend-host-hooks/ResourceInteractions.tsximport { useMemo, useState } from "react";
import { draftStringField, type FavoriteTarget, type ResourceReferenceIdentity } from "@nexia/sdk";
import { AppRouteFrame, FavoriteButton, InspectorAction, NxButton, NxOperatingUnitSelector,
ResourceInspectorPanel, ResourceInspectorState, ResourceListToolbarMoreMenu,
readResourceListParams, useReauthenticate, useRegisterDraftAction,
useRegisterResourceCreateReceiver, useRegisterTabActions } from "@nexia/sdk/host";
/** The record and favorite identity must come from an authorized response. */
export function ResourceInteractions({ recordId, label, canEdit, favorite, units, onCreated, onRefresh, onSensitiveAction }: {
recordId: string; label: string; canEdit: boolean; favorite: FavoriteTarget | null;
units: Array<{ value: string; label: string }>;
onCreated: (ref: ResourceReferenceIdentity) => void;
onRefresh: () => void;
onSensitiveAction: () => Promise<void>;
}) {
const [name, setName] = useState(label);
const [unit, setUnit] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const reauthenticate = useReauthenticate();
useRegisterResourceCreateReceiver({ target: { receiverKey: "example.related", receiverLabel: "Related record", resourceKey: "example.related" }, onCreated });
const actions = useMemo(() => [{ type: "example.describe", label: "Describe draft", effect: "read" as const,
run: () => ({ ok: true, message: "Draft read", data: { name } }) }], [name]);
useRegisterTabActions(actions);
useRegisterDraftAction({ resourceKey: "example.record", resourceId: recordId, actionType: "example.edit", label: "Edit draft", enabled: canEdit,
fields: { name: draftStringField(name, label, setName, { minLength: 1, maxLength: 120, trim: true }) } });
const list = readResourceListParams(new URLSearchParams(window.location.search));
return <AppRouteFrame appKey="example" title={label} subtitle="Record details"
actions={<ResourceListToolbarMoreMenu label="More" items={[{ id: "refresh", label: "Refresh", onSelect: onRefresh }]} />}>
<p>List page: {list.page}</p>
<label>Name <input value={name} disabled={!canEdit} onChange={(event) => setName(event.target.value)} /></label>
<NxOperatingUnitSelector ariaLabel="Operating unit" value={unit} options={units} onChange={setUnit} />
<ResourceInspectorPanel actions={<>{favorite ? <FavoriteButton target={favorite} /> : null}
<InspectorAction id="refresh" label="Refresh" permission="example.record.read" onSelect={onRefresh} /></>}>
<ResourceInspectorState>{label}</ResourceInspectorState>
</ResourceInspectorPanel>
{canEdit ? <NxButton onClick={() => void (async () => { try { setError(null); await reauthenticate(); await onSensitiveAction(); } catch { setError("Action was not completed."); } })()}>Confirm sensitive action</NxButton> : null}
{error ? <p role="alert">{error}</p> : null}
</AppRouteFrame>;
}Dashboard metric
docs/developers/examples/frontend-host-hooks/DashboardMetric.tsximport { useQuery } from "@tanstack/react-query";
import type { AgentComponentRendererProps } from "@nexia/sdk";
import { NxEmptyView, NxStatCard, useAgentToolDataFreshness, useAgentToolDataInvalidation,
useDashboardDataSource, useDashboardWidgetAutoHeight, useWidgetQueryRuntime } from "@nexia/sdk/host";
/** The declared tool enforces tenant, actor and organization scope on the server. */
export function DashboardMetric({ spec, preview = false }: AgentComponentRendererProps) {
const runtime = useWidgetQueryRuntime();
const ref = useDashboardWidgetAutoHeight(spec.props.widgetId);
const key = ["example.pending-count", runtime.tenantId, "legalEntityPublicIds" in runtime ? runtime.legalEntityPublicIds : null];
useAgentToolDataInvalidation(!preview);
useDashboardDataSource(key, runtime.supportsRealtimeInvalidation && !preview);
const freshness = useAgentToolDataFreshness({ enabled: true, refreshMs: 60_000, preview });
const result = useQuery({ queryKey: key, queryFn: ({ signal }) => runtime.query<{ value: number }>("example.pending-count", {}, signal), retry: false, ...freshness });
return <div ref={ref}>{result.isError ? <NxEmptyView kind="error" /> :
<NxStatCard label="Pending records" value={result.data?.value ?? "—"} loading={result.isLoading} />}</div>;
}Dashboard registration
docs/developers/examples/frontend-host-hooks/dashboard-registration.tsimport { registerAgentComponent, registerLazyAgentComponent } from "@nexia/sdk/host";
import { DashboardMetric } from "./DashboardMetric";
// Choose one registration per component name; the lazy variant loads on demand.
export function registerDashboardComponents() {
registerAgentComponent("example.PendingCount", DashboardMetric);
registerLazyAgentComponent("example.LazyPendingCount", () => import("./DashboardMetric").then((module) => ({ default: module.DashboardMetric })));
}Report date filter
docs/developers/examples/frontend-host-hooks/InsightsFilter.tsximport { NxInsightFilterBar, useInsightFilterState } from "@nexia/sdk/host";
/** Feed the selected dates into the authorized report query. */
export function InsightsFilter({ onRange }: { onRange: (from: string, through: string) => void }) {
const filter = useInsightFilterState({ defaultRange: "ytd" });
return <section><NxInsightFilterBar filter={filter} presets={["30d", "90d", "ytd", "custom"]} />
<button type="button" onClick={() => onRange(filter.from, filter.through)}>Apply dates</button></section>;
}File and background operations
docs/developers/examples/frontend-host-hooks/FileOperations.tsximport { useState } from "react";
import { NxButton, openFile, useDataMigrationBackgroundOperation, useUploadFile, useUploadMedia } from "@nexia/sdk/host";
/** The App supplies a host-supported purpose and an authorized status ticket. */
export function FileOperations({ tenantId, purpose, downloadHref, ticket }: {
tenantId: string; purpose: string; downloadHref: string; ticket: string;
}) {
const uploads = useUploadFile();
// Uploads an actor-owned file scoped to this App; it does not assign a business owner or legal entity.
// Link the file through the App attachment contract before using owner-scoped reads.
const media = useUploadMedia(tenantId);
const operation = useDataMigrationBackgroundOperation();
const [status, setStatus] = useState("");
const [busy, setBusy] = useState(false);
async function run(action: () => Promise<void>) {
setBusy(true); setStatus("");
try { await action(); } catch { setStatus("Operation failed. Retry when ready."); } finally { setBusy(false); }
}
return <section aria-label="File operations">
<label>Upload media <input type="file" disabled={busy} onChange={(event) => {
const file = event.target.files?.[0]; event.target.value = "";
if (file) void run(async () => { const result = await media.mutateAsync(file); setStatus(`Uploaded ${result.original_name}`); });
}} /></label>
<label>Stage import file <input type="file" disabled={busy} onChange={(event) => {
const file = event.target.files?.[0]; event.target.value = "";
if (file) void run(async () => {
const task = uploads.uploadFile({ purpose, file });
const prepared = await task.result;
const ready = await uploads.waitForCompletion(prepared.upload.id);
setStatus(`Upload ${ready.state}`);
});
}} /></label>
<NxButton disabled={busy} onClick={() => void run(async () => { await openFile(downloadHref); })}>Download</NxButton>
<NxButton disabled={busy} onClick={() => void run(async () => {
await operation.wait(ticket, { onProgress: (progress) => setStatus(`Processing ${progress}%`) });
setStatus("Operation completed.");
})}>Check submitted operation</NxButton>
{status ? <p role="status">{status}</p> : null}
</section>;
}Signature preparation
docs/developers/examples/frontend-host-hooks/SignaturePreparation.tsximport type { ComponentProps } from "react";
import { SignatureAuthenticationMethodSelector, SignatureInvitationChannelSelector,
SignatureRequestPreparationEditor, SignatureRequestPreparationExactPreview,
SignatureRequestPreparationPlacementEditor, SignatureSingleRequestDialog } from "@nexia/sdk/host";
/** All state and callbacks come from the App's authorized preparation endpoints. */
export function SignaturePreparation({ step, invitation, authentication, editor, placement, preview, request }: {
step: "capabilities" | "edit" | "placement" | "review" | "request";
invitation: ComponentProps<typeof SignatureInvitationChannelSelector>;
authentication: ComponentProps<typeof SignatureAuthenticationMethodSelector>;
editor: ComponentProps<typeof SignatureRequestPreparationEditor>;
placement: ComponentProps<typeof SignatureRequestPreparationPlacementEditor>;
preview: ComponentProps<typeof SignatureRequestPreparationExactPreview>;
request: ComponentProps<typeof SignatureSingleRequestDialog>;
}) {
return <>
{step === "capabilities" ? <>
<SignatureInvitationChannelSelector {...invitation} />
<SignatureAuthenticationMethodSelector {...authentication} />
</> : null}
{step === "edit" ? <SignatureRequestPreparationEditor {...editor} /> : null}
{step === "placement" ? <SignatureRequestPreparationPlacementEditor {...placement} /> : null}
{step === "review" && !editor.dirty && !editor.saving ? <SignatureRequestPreparationExactPreview {...preview} /> : null}
{step === "request" ? <SignatureSingleRequestDialog {...request} /> : null}
</>;
}Resource reference picker
docs/developers/examples/frontend-host-hooks/ReferencePicker.tsximport { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { allowsManualReferenceFallback, isResourceReferenceBlocked, parseResourceReferenceOptionPage,
resourcePickerRevalidation, resourceReferenceOptionsRoute, resourceReferencePickerQueryKey,
RESOURCE_PICKER_STALE_TIME_MS, savedResourceReferencePresentation, type ResourceReferenceIdentity } from "@nexia/sdk";
import { api, NxCombobox } from "@nexia/sdk/host";
/** The host selector and the eventual App write both enforce authorization. */
export function ReferencePicker({ tenantId, ownerId, saved, onSelect }: {
tenantId: string; ownerId: string | null; saved: ResourceReferenceIdentity | null;
onSelect: (ref: ResourceReferenceIdentity) => void;
}) {
const [search, setSearch] = useState("");
const resourceKey = "example.related";
const scope = { tenantId, legalEntityPublicId: ownerId, resourceKey };
const query = useQuery({ queryKey: resourceReferencePickerQueryKey({ ...scope, purpose: "example.record.related", dependencies: [search] }),
staleTime: RESOURCE_PICKER_STALE_TIME_MS,
queryFn: async ({ signal }) => parseResourceReferenceOptionPage((await api.get<unknown>(resourceReferenceOptionsRoute(ownerId, resourceKey,
{ consumerResourceKey: "example.record", consumerField: "related" }), { signal, params: { search, page: 1 } })).data, resourceKey) });
if (query.isError) return <p role="alert">Reference lookup failed.</p>;
const status = query.data?.meta.dependency_state;
if (status && isResourceReferenceBlocked(status)) return <p role="alert">Reference is unavailable ({status}).</p>;
if (status && allowsManualReferenceFallback(status)) return <p>The related App is absent; a manual fallback may be offered.</p>;
const options = (query.data?.data ?? []).map((item) => ({ value: item.reference.resource_id, label: item.reference.display }));
const snapshot = saved && status ? savedResourceReferencePresentation(saved, status) : null;
if (saved && snapshot && !options.some((option) => option.value === saved.resource_id)) options.push({ value: saved.resource_id, label: snapshot.display });
return <NxCombobox ariaLabel="Related record" placeholder="Select a record" value={saved?.resource_id ?? null} options={options}
searchValue={search} onSearchChange={setSearch} loading={query.isLoading} revalidateOnOpen={resourcePickerRevalidation(query)}
onChange={(id) => { const item = query.data?.data.find((option) => option.reference.resource_id === id); if (item) onSelect(item.reference); }} />;
}Migration completion
docs/developers/examples/frontend-host-hooks/MigrationHelpers.tsimport { createDataMigrationSessionCheckpointStore, dataMigrationRunPublicId, dataMigrationUploadAccept,
isDataMigrationOperationAccepted } from "@nexia/sdk";
import { useDataMigrationBackgroundOperation } from "@nexia/sdk/host";
// Session memory is a UI checkpoint, not proof of a server-side completed run.
const checkpoints = createDataMigrationSessionCheckpointStore<{ ticket: string }>();
export const acceptedFileTypes = dataMigrationUploadAccept(["csv", "xlsx"]);
export function useObserveImport() {
const operations = useDataMigrationBackgroundOperation();
return async (response: unknown) => {
if (!isDataMigrationOperationAccepted(response)) return dataMigrationRunPublicId(response);
checkpoints.remember("example.import", { ticket: response.ticket });
const result = await operations.wait<unknown>(response, { continueInBackground: true });
const runId = dataMigrationRunPublicId(result);
if (runId) checkpoints.delete("example.import");
return runId;
};
}Contract helpers
docs/developers/examples/frontend-host-hooks/ContractHelpers.tsimport { canForAnyPopulation, canForPopulation, CompositionSpecValidationError, documentDataFieldIdentity,
formatNumber, isAppAvailabilityState, isHandoffResultState, isResourceReferenceStatus, isRetryableFailure,
organizationTargetQueryParams, parseCompositionSpec, parseOrganizationTargetListSearchParams,
permitsManualFallback, projectSignatureCapabilityCatalog, readOrganizationListScope,
signatureCapabilityIdentity, writeOrganizationListScope, type DocumentDataFieldBinding, type SubjectPopulation } from "@nexia/sdk";
/** Invalid URL scopes must block the query, not silently broaden it. */
export function scopedQuery(search: URLSearchParams) {
const scope = readOrganizationListScope(search, "legal-entity-list");
if (scope.invalid) throw new Error("Invalid organization scope");
const validated = parseOrganizationTargetListSearchParams(search);
return organizationTargetQueryParams(validated);
}
export function setScope(search: URLSearchParams, legalEntityPublicIds: string[]) {
return writeOrganizationListScope(search, legalEntityPublicIds.length ? { legalEntityPublicIds } : {});
}
/** Presentation permission hints do not replace server-side checks. */
export function presentation(populations: Record<string, SubjectPopulation[]>, amount: string | null, locale: string) {
return { canEditSelf: canForPopulation(populations, "example.record.update", "self"),
canReadTeam: canForAnyPopulation(populations, "example.record.read", ["direct_reports", "operating_unit"]),
amount: formatNumber(amount, locale) };
}
export function parseSavedComposition(value: unknown) {
try { return parseCompositionSpec(value); }
catch (error) { if (error instanceof CompositionSpecValidationError) return null; throw error; }
}
export function dependencyMessage(value: unknown) {
if (isResourceReferenceStatus(value)) return `Reference: ${value}`;
if (isAppAvailabilityState(value)) return permitsManualFallback(value) ? "App absent; manual fallback allowed" : `App: ${value}`;
if (isHandoffResultState(value)) return isRetryableFailure(value) ? "Retry is available" : `Handoff: ${value}`;
return "Unknown status";
}
export function signatureCatalog(response: unknown, binding: DocumentDataFieldBinding) {
return { catalog: projectSignatureCapabilityCatalog(response),
email: signatureCapabilityIdentity("invitation_channel", "email"), fieldKey: documentDataFieldIdentity(binding) };
}Approval submission
docs/developers/examples/frontend-host-hooks/ApprovalSubmission.tsimport { queueApprovalRequest } from "@nexia/sdk";
import { api } from "@nexia/sdk/host";
/** Generate the key once per user submission and retain it across uncertain responses. */
export function submitForApproval(ownerId: string, draftId: string, key: string, body: Record<string, unknown>) {
return queueApprovalRequest(api, ownerId, `/example/records/${encodeURIComponent(draftId)}/submit`, body,
{ headers: { "Idempotency-Key": key } }, draftId);
}Test host setup
docs/developers/examples/frontend-host-hooks/TestHost.tsimport { appTestI18n, appTestServer, configureNexiaAppFrontendTestHost } from "@nexia/sdk";
/** Call once in the App test setup with that suite's own i18n and mock server. */
export function configureTestHost(i18n: { changeLanguage: (language: string) => unknown }, server: { use: (...handlers: unknown[]) => void }) {
configureNexiaAppFrontendTestHost({ i18n, server });
}
export function prepareTest(language: string, ...handlers: unknown[]) {
appTestServer.use(...handlers);
return appTestI18n.changeLanguage(language);
}Presentation and cache helpers
docs/developers/examples/frontend-host-hooks/PresentationHelpers.tsimport { buildAppCatalogTree, resourceFieldValue, resourceReferencePickerQueryRoot,
type AppCatalogLeaf } from "@nexia/sdk";
import type { QueryClient } from "@tanstack/react-query";
/** The server has already filtered these entries for the current actor. */
export function authorizedCatalog(entries: AppCatalogLeaf[]) {
return buildAppCatalogTree(entries);
}
/** Use with an App-owned resource form field's view function. */
export function displayNote(note: string | null) {
return resourceFieldValue(note, { empty: note === null || note === "" });
}
/** Call after the owner confirms a successful write, not after dispatch. */
export function refreshRelatedChoices(client: QueryClient, tenantId: string, ownerId: string | null) {
return client.invalidateQueries({ queryKey: resourceReferencePickerQueryRoot({ resourceKey: "example.related", tenantId, legalEntityPublicId: ownerId }) });
}