예제
문맥과 변경 피드백
인가된 문맥과 프로젝션 알림, 공통 피드백을 사용합니다.
예제 유형 레시피
개요
사용자 문맥·변경 알림·피드백
앱 화면에서 호스트가 제공하는 문맥과 UI 동작을 사용합니다. 이 예제는 앱 검색 입력을 지연 처리하고, 인가된 Resource의 프로젝션 변경을 구독하며, 호스트의 날짜 형식과 공통 피드백을 사용해 다시 조회합니다. 실제 인가된 API 요청, Resource 식별자와 안정적인 콜백은 부모 화면이 제공합니다. 프로젝션 신호는 데이터나 권한이 아니므로 서버에서 다시 조회하고 권한을 확인하세요. 이 예제는 화면 표시 상태에서만 구독하며, 실제 업무에 맞는 갱신 정책을 선택해야 합니다.
Attachments.tsx는 저장된 Resource 첨부파일의 첫 페이지를 조회하고 업로드와 삭제 확인을 보여 줍니다. 부모 화면에서 접근 권한을 확인한 뒤 표시하고, 서버에서도 모든 요청을 인가해야 합니다. 전체 목록에는 페이지 이동을 구현하고 예제 문구를 앱에 맞게 번역하세요.
추가 호스트 계약
OrganizationLookups.tsx는 소속, 배정 가능, 적용 대상 조회를 구분합니다. 조직 관리는 인가된 경로에서 사용하고 페이지 처리는 업무에 맞게 구현하세요.ResourceInteractions.tsx는 경로 프레임, Inspector, 생성 후 복귀, 로컬 초안 액션과 재인증을 보여 줍니다. 서버가 인가한 식별자와 액션을 전달하세요. 초안은 저장이 아니며 실제 쓰기는 서버에서 인가해야 합니다.DashboardMetric.tsx와dashboard-registration.ts는 도구 기반 위젯과 즉시·지연 등록을 보여 줍니다. App이 선언한 도구로 바꾸고 질의 키에 테넌트와 조직 범위를 포함하세요.InsightsFilter.tsx는 양 끝 포함 날짜를 보고서에 전달합니다.FileOperations.tsx는 호스트가 지원하는 업로드 용도를 사용하고 검증 완료를 기다리며 인가된 파일과 기존 백그라운드 작업을 엽니다. 마이그레이션을 시작하거나 재실행하지 않습니다.SignaturePreparation.tsx의 상태는 인가된 리비전별 준비 API에서 가져오세요. 단계에 맞는 편집기를 선택하고 저장된 현재 리비전의 미리보기를 표시하며 요청 대화상자에 App의 생성·제출 함수를 연결합니다.
bindNexiaAppRequestServices는 SDK 빌드 계층, configureNexiaAppFrontendHost는 Core의 초기화 경로입니다. 일반 App에서 직접 호출하지 마세요. 예제는 호스트 라우터·쿼리·권한·요청 문맥을 전제로 합니다. 문구를 번역하고 업무에 필요한 페이지 이동·재시도·인가 처리를 구현하세요.
ReferencePicker.tsx는 인가된 선택기에서 의존 App 부재와 차단 상태를 구분합니다. MigrationHelpers.ts는 제출된 작업을 재실행하지 않고 관찰하며, 완료 증거는 서버가 소유한 실행 기록입니다. ContractHelpers.ts는 조직 범위, 권한 표시, 상태 처리와 파싱을 보여 줍니다.
ApprovalSubmission.ts는 응답이 불확실해도 같은 멱등성 키를 유지합니다. 접수는 결재 완료가 아니므로 인가된 경로에서 결과를 확인하세요. TestHost.ts는 App 테스트의 자체 픽스처를 연결합니다.
PresentationHelpers.ts는 인가된 카탈로그를 묶고 빈 필드 값을 표시하며 쓰기가 확인된 뒤 소유 범위의 참조 캐시를 갱신합니다. RESOURCE_REFERENCE_STATUSES, APP_AVAILABILITY_STATES, HANDOFF_RESULT_STATES, APPROVAL_STATES, APPROVAL_STEP_KINDS와 서명 문서 데이터 목록은 각 계약의 상태값입니다. 표시 문구로 대체하거나 권한으로 해석하지 마세요. DMN_EDITOR_HIT_POLICIES는 편집기 선택지입니다. NEXIA_READ_ONLY_HEADER는 선언된 읽기 전용 요청의 전송 계약이며 인가 우회 수단이 아닙니다. 이전 이름 allowsManualAppFallback, isRetryableHandoffFailure 대신 permitsManualFallback, isRetryableFailure를 사용하세요.
SIGNATURE_DOCUMENT_DATA_CLASSIFICATIONS, SIGNATURE_DOCUMENT_DATA_FIELD_TYPES, SIGNATURE_DOCUMENT_DATA_FORMATTERS, SIGNATURE_DOCUMENT_DATA_LOOKUP_MODES, SIGNATURE_DOCUMENT_DATA_STATUSES는 서명 데이터 계약 값이며 사용 권한이 아닙니다. queryKeys는 호스트 조회 키를 제공하므로 인가 범위를 함께 지정하세요. parseRefreshHint와 resolveTokens는 대시보드 설정, isAuthorityRevocationError는 접근 권한 상실 처리에 사용합니다. withOperatingUnit은 기존 단일 조직 URL용이며 신규 목록은 페이지 조직 범위를 사용합니다. NX_LINE_CHART_MAX_SERIES, NX_DONUT_MAX_SEGMENTS, chartCategoricalColor는 차트 표시를 돕습니다.
포함된 파일
문맥과 변경 알림
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 첨부파일
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>;
}조직과 참조 조회
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 상호작용
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>;
}대시보드 지표
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>;
}대시보드 등록
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 })));
}보고서 날짜 필터
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>;
}파일과 백그라운드 작업
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>;
}서명 준비
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 참조 선택
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); }} />;
}마이그레이션 완료 확인
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;
};
}계약 도우미
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) };
}결재 제출
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);
}테스트 호스트 설정
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);
}표시와 캐시 도우미
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 }) });
}